Basic of Rails routing -rails routes basic hack

Here I am going to focus on only basic routing technic of Rails.

If you are new in rails. Just wanted to remind you.

First go to Rails project’s “public” folder and delete or rename the index.html file. If index.html file is there then default routing will not run.

If you want Users controller’s index page as a home page of site then go for this code in routes.rb file.

map.connect ”, { :controller => ‘users’, :action => ‘index’ }

In view you can use link for home page and logo of site(basic hack)

<%= link_to(“HOME”,{:controller=>’/’}) %>


ActiveRecord-JDBC is for use with JRuby only….

Few days back when i tred to run my rails project. I got an error saying

ActiveRecord-JDBC is for use with JRuby only
jdbc-mysql is only for use with JRuby
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:76:in `establish_connection’: Please install the jdbcmysql adapter: `gem install activerecord-jdbcmysql-adapter` (no such file to load — java) (RuntimeError)
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:60:in `establish_connection’
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/connection_specification.rb:55:in `establish_connection’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:417:in `initialize_database’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:141:in `process’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:113:in `send’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/initializer.rb:113:in `run’
from /var/www/html/HOO/trunk/config/environment.rb:9
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:156:in `require’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:521:in `new_constants_in’
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:156:in `require’
from /usr/lib/ruby/gems/1.8/gems/rails-2.3.2/lib/commands/server.rb:84
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require’

I am using Fedora 9 as Os and mysql as database.

I read all the error than i got to know. I need to change my database.yml file.

in that file i have following text;

adapter: jdbcmysql

i changed that to:

adapter: jdbcmysql

socket: /var/lib/mysql/mysql.sock

I thoutht jruby database issue but not. the database setting is an issue.

Fixed this issue: Building native extensions. This could take a while…

I got this error when i tried to install various ruby gems on system.

I am using the Fedoa 9 as OS.  I tried a lot to fix this issue and googled lot but not found exactly solution.

later on realize some of latest software are not installed on OS that’s why i am getting these kind of error.

you need to install proper software on Fedora box.

# yum install ruby ruby-libs ruby-mode ruby-rdoc ruby-irb ruby-ri ruby-docs

#yum install gcc-c++

this is the solution.


Compress the server response with Nginx

Maybe you aware with apache “mod_gzip and mod deflate”

Compress the server response with Nginx

Web page compression is not a new technology, but it has recently gained higher recognition in the minds of IT administrators and managers because of the rapid ROI it generates. Compression extensions exist for most of the major Web server platforms

For Apache Normally use following syntax:

mod_gzip_item_exclude file \.js$
mod_gzip_item_exclude mime ^text/css$

mod_gzip_item_include file \.html$
mod_gzip_item_include file \.shtml$
mod_gzip_item_include file \.php$
mod_gzip_item_include mime ^text/html$

mod_gzip_item_include file \.txt$
mod_gzip_item_include mime ^text/plain$

mod_gzip_item_include file \.css$
mod_gzip_item_include mime ^text/css$

We used gzip and compressing files technology with various browers. You need following browser support for this.

  • Accept-encoding: gzip
  • Accept-encoding: gzip, deflate

For Nginx i used following code in Nginx.conf file:

# Compression of response time
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 9;
gzip_http_version 1.0;
gzip_min_length 0;
gzip_types text/plain text/html text/css image/x-icon image/png image/jpg image/jpeg text/js text/php;
gzip_vary on;

Nginx Rule for Rails Application

Use following code for setting up Nginx for rails.

http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;</code>

log_format  main  '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

# Timeouts
client_body_timeout   5;
client_header_timeout 5;
keepalive_timeout     55;
send_timeout          5;

upstream mongrel_cluster {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
server {
listen       80;
server_name  localhost.localdomain;
#charset koi8-r;
#access_log  logs/host.access.log  main;

#for images routing
location ~* ^/(images|stylesheets|javascripts).+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
{
root /var/www/html/Projects/Project_Name/public;
}
# concurs with nginx's one

location  / {
proxy_pass	http://mongrel_cluster;
#Fix for host name and redirection to domain

}

}

<code>

Install Apatana Studio on Fedora 9

Installation of Apatana in Detail

1. Download zip file from this location(http://www.aptana.com/studio/download)
File name:Aptana_Studio_Setup_Linux_1.2.7.zip
2. Then uncompress the .zip file. and copy the resulting ‘aptana’ folder under ‘/home/siwan’.(siwan is my username for fedora, you have replace your username)
3. Install xulrunner (for install xulrunner user following command, Became root first)
yum install xulrunner
or follow this step
Down load xulrunner from this url
http://releases.mozilla.org/pub/mozilla.org/xulrunner/releases/1.8.1.3/contrib/linux-i686/xulrunner-1.8.1.3.en-US.linux-i686-20080128.tar.gz
Unarchive using file roller to get a ‘xulrunner’ folder.
Open a terminal, and type the following commands, changing the path in the last line ie nigel to your username.
(for install xulrunner user following command, Became root first)

    mkdir /usr/lib/xulrunner
    cp -r /home/nigel/Download/xulrunner/* /usr/lib/xulrunner

4. Create a new file called say ‘aptana.sh’ and make it executable
use this command for make file executable.
Became root user first.
cd /home/siwan/aptana/
chmod +x aptana.sh
5. Copy the following into that text file

#!/bin/sh
MOZILLA_FIVE_HOME=/usr/lib/xulrunner
if [ $LD_LIBRARY_PATH ]; then
LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH
else
LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME
fi
export MOZILLA_FIVE_HOME LD_LIBRARY_PATH
/home/siwan/aptana/AptanaStudio

Then run the aptana.sh file.
Enjoy with Aptana Studio

Memcached Server with Rails

To install memcached server on linux/fedora box
yum install memcached

Find help for memcached commands and option
memcached -help

Start memcached server(11211 is default port Number for memcached server)
memcached -m 500 -l 192.168.2.4 -p 11211 -vv
(192.168.2.4 this is my local ip address you can cahnge that)

Stop the Memcached server
ps -ef|grep memcached
kill PROCESS_ID

start memcached server with
memcached -m 500 -l 192.168.2.4 -p 11211 -vv

How to install on Windows server:
1.  Downloaded this Win32 port of memcached by Kenneth Dalgleish.(download from following url)
http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching
2. Extracted the files to C:\Program Files\memcached
3. Opened a command prompt in the folder and installed memcached as a service using memcached -d install
4. Started the service using net start “memcached Server”

How to use memcache in Rails app?
Open  /config/environments/development.rb for development mode,
production.rb for production mode.
paste following line into file.
config.cache_store = :mem_cache_store, ‘127.0.0.1’, ‘127.0.0.1:11211’ , { :namespace => ‘dev’ }
(127.0.0.1 this is my local ip address you can cahnge or point out to any server where memcached server is running)
Restart mongrel server. you are ready to use memcached server

How to use in Rails
@user= User.find(1)—–OLD Code

New Code With Caching:
@user = cache([‘User’,1],:expires_in => 30.minutes) do
User.find(1)
end

deconstructing date_select in rails

// Reconstruct a date object from date_select helper form params

// place this code into your application.rb file
def build_date_from_params(field_name, params)
Date.new(params["#{field_name.to_s}(1i)"].to_i,
params["#{field_name.to_s}(2i)"].to_i,
params["#{field_name.to_s}(3i)"].to_i)
end

//You can changes order of displaying into view
<%= date_select ‘from’, ‘date’ ,:order => [:day, :month, :year] %>
<%= date_select ‘to’, ‘date’,:order => [:day, :month, :year]  %>

//goes into controller -- add your own error handling/defaults, please!
@from = build_date_from_params(:date, params[:from])
@to = build_date_from_params(:date, params[:to])

Comparing date time into controller

@users_reports = User.find(:all, :conditions=>[‘created_at >= ? and created_at < ?’, @to, @from])

Creating a Windows service

For this I used Daniel Berger’s win32-service package. This is a great package that does literally everything for you to enable you to create a nice Windows service. Just install the gem like this:

gem install win32-service

I used examples/daemon_test.rb as the base template to make my Windows Service. This piece of code contains all that is needed to run the code snippet above as a service. In this file you will find a class called Daemon that has a number of methods necessary for running a Windows service. Put in the necessary requires and place your ActiveRecord initialization code at the beginning of the code. Then under service_main, while the status == RUNNING, put in the main processing code, minus the loop. Your code could possibly look something like this (don’t cut and paste this code, just use it as a reference):

require 'rubygems'
require 'logger'
require 'active_record'
require 'c:/myrailsapp/app/models/message' # remember to put in the absolute path here
require "win32/service"
include Win32

ActiveRecord::Base.establish_connection({
:adapter  => "mysql",
:host     => "localhost",
:username => "xxx",
:password => "xxx",
:database => "mydatabase"
})

# I start the service name with an 'A' so that it appears at the top
SERVICE_NAME = "MyProcess Service"
SERVICE_DISPLAYNAME = "MyProcess"

if ARGV[0] == "install"
svc = Service.new
svc.create_service{ |s|
s.service_name = SERVICE_NAME
s.display_name = SERVICE_DISPLAYNAME
s.binary_path_name = 'ruby ' + File.expand_path($0)
s.dependencies = []
}
svc.close
puts "installed"
elsif ARGV[0] == "start"
Service.start(SERVICE_NAME)
# do stuff before starting
puts "Ok, started"
elsif ARGV[0] == "stop"
Service.stop(SERVICE_NAME)
# do stuff before stopping
puts "Ok, stopped"
elsif ARGV[0] == "uninstall" || ARGV[0] == "delete"
begin
Service.stop(SERVICE_NAME)
rescue
end
Service.delete(SERVICE_NAME)
# do stuff before deleting
puts "deleted"
elsif ARGV[0] == "pause"
Service.pause(SERVICE_NAME)
# do stuff before pausing
puts "Ok, paused"
elsif ARGV[0] == "resume"
Service.resume(SERVICE_NAME)
# do stuff before resuming
puts "Ok, resumed"
else

if ENV["HOMEDRIVE"]!=nil
puts "No option provided.  You must provide an option.  Exiting..."
exit
end

## SERVICE BODY START
class Daemon
logger = Logger.new("c:/myprocess.log")

def service_stop
logger.info "Service stopped"
end

def service_pause
logger.info "Service paused"
end

def service_resume
logger.info "Service resumed"
end

def service_init
logger.info "Service initializing"
# some initialization code for your process
end

## worker function
def service_main
begin
while state == RUNNING || state == PAUSED
while state == RUNNING

# --- start processing code
messages = Message.find :all,
:conditions => ['sent = (?)', 0], # check if the message has been sent
:limit => 20 # retrieve and process 20 at a time

# array of threads
threads = []

# iterate through each message
for message in messages do
# start a new thread to process the message
threads < < Thread.new(message) do |message|
# process the message here ...
message.sent = 1
message.save
end

# don't finish until all threads are done
threads.each do |t|
begin
# join the threads when it's done
t.join
rescue RuntimeError => e
# do some rescuing
puts “Failed: #{e.message}”
end
end
end

# — end processing code

end
if state == PAUSED
# if you want do something when the process is paused
end
end
rescue StandardError, Interrupt => e
logger.error “Service error : #{e}”
end
end
end

d = Daemon.new
d.mainloop

end #if

Important to note that you need to put in the absolute path in the require as the service wouldn’t be starting at the Rails app.

Now you can install and start the Windows service (assuming the code is written in a file called ‘message_service.rb’:

c:/>ruby message_service.rb install
c:/>ruby messag_service.rb start

You can also control it from your Windows Services MMC console. What you have now is a Windows service that loops around until there is a message record in your database that is not sent (sent = 0). If there are, it will retrieve up to 20 messages at a go and process them with a thread each (parallelizing the processing to make it faster). Once it is processed, it will indicate the meesage has been sent (sent = 1) and loop again. Now you can happily create messages from your Rails app and stuff them into the database, while your message processor will process them separately.