How to debug a Merb Application

July 10th, 2008

Merb provides the “debugger” method which makes debugging easy. Insert “debugger” in the code that you want to debug. For example:

def update
   debugger # add this line
   cool_songs = Song.find_the_cool_ones
   cool_songs.reset_new_additions
   ...
end

Next start the app in debug mode:

merb -D

Now you can step through the debugger terminal and use the various available commands to debug your code. Type ‘help’ at the terminal to get a list of available commands.

(rdb:3) help
help
ruby-debug help v0.10.1
Type 'help ‘ for help on a specific command

Available commands:
backtrace  delete   enable  help    next  quit     show    trace
break      disable  eval    info    p     reload   source  undisplay
catch      display  exit    irb     pp    restart  step    up
condition  down     finish  list    ps    save     thread  var
continue   edit     frame   method  putl  set      tmate   where

How to delete rails log files

June 20th, 2008

The following command will recursively delete any development.log file within your home directory:

find ~/ -name development.log  -exec /bin/rm -f {} \;

Using nginx + mongrel + rails on Ubuntu

October 5th, 2007

STEP 1
Install Nginx. Get the source code from here. Before you compile make sure you have SSL libraries if you plan on using the SSL mode. To get the ssl libraries run:

sudo aptitude install openssl libssl-dev

To compile:


./configure --with-http_ssl_module
make
sudo make install

To start nginx run


sudo /usr/local/nginx/sbin/nginx

STEP 2
Edit

/usr/local/nginx/conf/nginx.conf

file to setup configuration for your rails app and mongrel cluster. Here is a sample of nginx.conf file:


worker_processes  1; 

error_log  logs/error.log;
error_log  logs/error.log  notice; 

pid        logs/nginx.pid; 

events {
    worker_connections  1024;
} 

http
{
        include       conf/mime.types;
        default_type  application/octet-stream;
        server_names_hash_bucket_size 128; 

        sendfile        on;
        tcp_nopush     on; 

        keepalive_timeout  65;
        tcp_nodelay        on; 

        upstream mongrel_test {
            server 127.0.0.1:8000;
            server 127.0.0.1:8001;
            server 127.0.0.1:8002;
        } 

        gzip on;
        gzip_min_length  1100;
        gzip_buffers     4 8k;
        gzip_types       text/plain; 

        # ************************ server conf begins **********************
        server
        {
                listen       80;
             server_name  servername.com;
             root    /home/shovan/apps/oas/public; 

             access_log  off;
             rewrite_log on; 

            # this rewrites all the requests to the maintenance.html
            # page if it exists in the doc root. This is for capistrano's
            # disable web task
            if (-f $document_root/system/maintenance.html) {
              rewrite  ^(.*)$  /system/maintenance.html last;
              break;
            } 

                location ~ ^/$ {
                  if (-f /index.html){
                    rewrite (.*) /index.html last;
                  }
                   proxy_pass  http://mongrel_test;
                } 

                location / {
                  if (!-f $request_filename.html) {
                    proxy_pass  http://mongrel_test;
                  }
                  rewrite (.*) $1.html last;
                } 

                location ~ .html {
                                root    /home/shovan/apps/oas/public;
                } 

                   location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov)$ {
                  root /home/shovan/apps/oas/public;
                } 

                location / {
                    proxy_pass  http://mongrel_test;
                    proxy_redirect     off;
                    proxy_set_header   Host             $host;
                    proxy_set_header   X-Real-IP        $remote_addr;
                    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
                } 

        }

} # end of http

STEP 3

Set up your mongrel_cluster.yml file. Here is how it should look like:

 ---
cwd: /home/shovan/apps/oas
port: "8000"
environment: production
address: 127.0.0.1
pid_file: log/mongrel.pid
servers: 3

STEP 4
Now start the mongrel cluster using the following command:

 sudo mongrel_rails cluster::start

That should fire up the clusters. Restart ngnix and you should be able to see your rails app when you load up the url in the browser. If you get errors make sure you look at the logs to see whats going on. They can be really helpful.

Useful Linux Commands

September 21st, 2007

Disk Usage

To find out disk usage in your linux box type:

df -h

Memory Usage

To get a breakdown of memory information, run

cat /proc/meminfo

To get a sum of memory(RAM) size, run

 cat /proc/meminfo | grep MemTotal

Process Details

To find details of processes that are running:

 ps -ef 

You can also do

ps -ef | grep ruby

to look for any ruby processes that are running on the machine.

List of files in a directory

ls | wc -l

Installing Ruby bindings for SVN on Ubuntu

July 21st, 2007

I just spent four painful hours :( trying to setup Collaboa on my Ubuntu box. I hope to share my findings hoping it will save you guys some time.

Collaboa is a collaborative tool for developers using Subversion. It is written in rails and lets you do repository browsing, track issues, manage milestone, and view changes.

First thing you need to get is the ruby bindings for subversion. Please do not try version 1.3.25. It just won’t work.

STEP 1
You can download the ruby bindings for subversion here .

tar xzvf swig-1.3.31.tar.gzcd ./swig-1.3.31./configuremakesudo make install 

STEP 2
Download and install the latest version of Subversion

wget http://subversion.tigris.org/downloads/subversion-1.4.4.tar.gztar xzvf subversion-1.4.4.tar.gzcd subversion-1.4.4./configure –prefix=/usr/local –with-openssl –with-ssl –with-zlib make sudo make install 

STEP 3
Now, install the Ruby subversion bindings

make swig-rb
sudo make install-swig-rb
sudo apt-get install libsvn-ruby

Then start irb and do a ‘require “svn/core” to find out if u were able to install swig-rb properly.

Validations based on a Controller Method

June 21st, 2007

Sometimes i have ran into a situation where there was a need to validate a new record depending upon which method was used. For example I was capturing data for an event which had both domestic and international leads. There were different criteria for the two sets of data.

For eg: I needed to validate presence of state, cost center for US leads and ignore those for international leads.

So i needed to figure out separate ways to handle the validations. Here is how I implemented it.

I defined two methods in my model: usa_validation? and international_validation?


  # validations only specific to usa leads
  attr_accessor :usa_validation

  def usa_validation?
    return usa_validation
  end

  def usa_validation=(value)
    @usa_validation = value
  end

  validates_presence_of :region, :if => :usa_validation?
  validates_presence_of :cost_center, :if => :usa_validation?

  # validations only specific to international leads
  attr_accessor :international_validation

  def international_validation?
    return international_validation
  end

  def usa_validation=(value)
    @usa_validation = value
  end

  validates_presence_of :country, :if => :international_validation?

In my controller i set the flag to true for US or international depending upon the case.


  def capture_usa_lead
    @lead = Lead.new(params[:lead])
    @lead.usa_validation =  true
    if @lead.save
      #display message
    else
      render  :layout => “lead”, :partial => “usa_form”
    end
  end
  def capture_international_lead
    @lead = Lead.new(params[:lead])
    @lead.international_validation = true
    if @lead.save
            #display message
    else
      render  :layout => “lead”, :partial => “international_form”
    end
  end

Rake Commands List

June 20th, 2007
rake db:fixtures:load          # Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y
rake db:migrate                # Migrate the database through scripts in db/migrate. Target specific version with VERSION=x
rake db:schema:dump            # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load            # Load a schema.rb file into the database
rake db:sessions:clear         # Clear the sessions table
rake db:sessions:create        # Creates a sessions table for use with CGI::Session::ActiveRecordStore
rake db:test:clone             # Recreate the test database from the current environment's database schema
rake db:test:clone_structure   # Recreate the test databases from the development structure
rake db:test:prepare           # Prepare the test database and load the schema
rake db:test:purge             # Empty the test database
rake log:clear                 # Truncates all *.log files in log/ to zero bytes
rake rails:freeze:edge         # Lock to latest Edge Rails or a specific revision with REVISION=X (ex: REVISION=4021) or a tag with TAG=Y (ex: TAG=rel_1-1-0)
rake rails:freeze:gems         # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:unfreeze            # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update              # Update both configs, scripts and public/javascripts from Rails
rake rails:update:configs      # Update config/boot.rb from your current rails install
rake rails:update:javascripts  # Update your javascripts from your current rails install
rake rails:update:scripts      # Add new scripts to the application script/ directory
rake stats                     # Report code statistics (KLOCs, etc) from the application
rake test                      # Test all units and functionals
rake test:functionals          # Run the functional tests in test/functional
rake test:integration          # Run the integration tests in test/integration
rake test:plugins              # Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name)
rake test:recent               # Test recent changes
rake test:uncommitted          # Test changes since last checkin (only Subversion)
rake test:units                # Run the unit tests in test/unit
rake tmp:cache:clear           # Clears all files and directories in tmp/cache
rake tmp:clear                 # Clear session, cache, and socket files from tmp/
rake tmp:create                # Creates tmp directories for sessions, cache, and sockets
rake tmp:pids:clear            # Clears all files in tmp/pids
rake tmp:sessions:clear        # Clears all files in tmp/sessions
rake tmp:sockets:clear         # Clears all files in tmp/sockets

Public Key Authentication

May 6th, 2007

Using public key authentication you can save yourself the hassel of remembering and entering password everytime you try to connect to a remote server. This process requires two files: a private key and a public key that identifies the local machine and the remote host.  Lets get started.

Step 1:

Enter the following command on the local machine.

ssh-keygen -t dsa 

It will ask you if you want to enter a pass phare. Ignore it.

That command creates two files

i) id_dsa : This is the private key
ii) id_dsa.pub : public key which you will copy to the remote host where u want to login using the public key authentication method
Step 2:

Copy the id_dsa.pub key to the remote host you want to access.

Step 3:

Log in to the remote host and add the id_dsa.pub file to the authorized_keys file which resides in your ~/.ssh/ directory. If the file and the directory does not exist then you have to create it.

Syntax for adding the public key (id_dsa.pub) to the authorized_keys file:

cat id_rsa.pub > authorized_keys

Now try logging into the remote host. You will notice that you no longer require password to get in. This is because your machine’s public key  is listed in the authorized_keys file that matches to your corresponding id_dsa private key that is located in your ~/.ssh folder.

How to setup synergy ( Mac OSX / Ubuntu)

May 5th, 2007

With the help of Synergy one can manange multiple computers/screens by using just one keyboard and mouse. So i found out after several painful months of using two sets of keyboard and mouse to switch between my Macbook and Ubuntu Desktop. I shall talk about the steps I took to get synergy to work on my Macbook and Ubuntu desktop. I chose to use my Macbook as the server and Ubuntu as the client.

Hostname of my Macbook(Server): isis
Hostname of my Ubuntu Desktop(Client) : venus
Please replace the hostnames in the following example with your correct names.

Step 1.
Download and install the source code from http://synergy2.sourceforge.net/
unzip the file install it on both computers.

./configure
make
sudo make install

Step 2 ( Configure Mac OS X server)
create a file called synergy.conf with the following content

section:  screens
# name the screens
isis:
venus:
end

section:  links
# telling synergy direction of the screens
# my macbook is on the left and Ubuntu is on the right
isis:
right = venus
venus:
left = isis
end

to start the synergy server

synergys -f --config syngery.conf

Step 3: ( starting Ubuntu Client)
Make sure you have installed synergy.Then run the following command.

synergyc -f isis
(syngergyc -f hostname-of-synergy-server)

You can also use the ip address of the synergy server.

For more information visit: http://synergy2.sourceforge.net/faq.html

VNCServer Problems

March 9th, 2007

If you are having problems accessing a machine which has vncserver running, then you should check if the firewall is blocking the port.

Normally you will get the following error if the remote host is reachable but the port to vncserver is blocked.

Exception connecting to hostname: Connection refused

You can try the following steps to open the port for Vncserver.

Step 1:
There are several ways to open up port for vncserver. One way is to edit the iptables.

$su
$cd /etc/sysconfig
$vi iptables

Step 2:

Insert the following line

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5901:5909 -j ACCEPT

right before the second last line

-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT

Step 3:
The next step would be to restart iptables.

# /sbin/service iptables restart

Now the machine (host) with the vncserver should be accessible from remote computers which has vncviewer installed.

To start vncserver:

vncserver -geometry 1024x768