Translate

March 3, 2013

How to Install ruby 2.0 with RVM

Ruby 2.0 was released on 24th February 2013, on the 20th birthday of Ruby.
Get the newest version with favorite ruby version manager rvm.
You must install libyaml because Ruby 2.0 deprecated syck in favor of psych.

Make sure you have the latest RVM:
rvm get stable

Execute following command from terminal after installing RVM:

# For Mac with Homebrew
brew install libyaml

# For Ubuntu systems
apt-get install libyaml-dev
rvm pkg install openssl
rvm install 2.0.0 --with-openssl-dir=$HOME/.rvm/usr  --verify-downloads 1
rvm use 2.0.0
rvm use 2.0.0

OR Simply use following
rvm get stable && rvm install ruby-2.0.0

January 21, 2013

Easy google currency conversion gem

When your app wants to convert local currency to any other currency using current exchange rate, then you can convert it using Google API. like http://www.google.com/ig/calculator?hl=en&q=100USD=?INR. This will give you a json string with the converted value. You need to parse the result and get the converted currency value in your app. You can use USD to Yen, EURO to USD etc .. using Google API.

There is a simple interface to handle this using Google API.
Convert any currency to any other currency using easy to use goog_currency gem
A simple Ruby interface for currency conversion using Google API.

How to use:
Add gem file in Gemfile

gem 'goog_currency'

Use bundle to get this gem installed on your system.
Now in your app code you can use functions like follows:
To Get pounds from usd simply use usd_to_gbp

amount = 223
pounds = GoogCurrency.usd_to_gbp(amount)

Get yen from ponds using gbp_to_jpy

amount = 223
yen = GoogCurrency.gbp_to_jpy(amount)

Similarly ....
pounds = GoogCurrency.jpy_to_gbp(amount)
usd = GoogCurrency.gbp_to_usd(amount) 

etc...

You have to pass the amount to those functions.

This will throw an exception in case of any error.
Throws GoogCurrency::Exception in case of any error. And,
Throws GoogCurrency::NoMethodException if conversion method syntax is invalid.

You can find the Source Code here
And Gem here

goog_currency License
MIT License This software is provided as is, use it your own risk.
Copyright (c)  Girish Sonawane

January 17, 2013

How to installing gems when no network

If you have a system with no network connection or you have very restricted firewall connection then its very difficult to install gems.Here is simple work around to solve such problem. You at least need a way to move the files on system.
  • Step 1: Install the required gem on internet connected computer. You can disable the document generation if you desire.
    $ gem install gem_name -i dir_name --no-rdoc --no-ri
    

  • Step 2:  RubyGems has downloaded all the .gem files and placed them in dir_name/cache. You need to Copy this directory to a USB pen drive or some thing else to move directory to the target system. you can use a secure network to transfer it.
  • $ cp -r dir_name/cache /path_to/usb_pen_drive/gems
    

  • Step 3: Install the gems on the target system from the local files
  • $ cd /path_to/usb_pen_drive/gems
    $ gem install --force --local *.gem
    
Thats it ... Your system has a required gem installed

December 12, 2012

Class Variables on Class, in Ruby


Class variable

You can declare class variables by using @@ for prefix of variable name, for instance: @@common

A class variable is shared among all objects of a class, and it is also accessible to the class methods that we'll describe later. There is only one copy of a particular class variable for a given class
Class variables must be initialized before they are used. Often this initialization is just a simple assignment in the body of the class definition.
Class variables can easily overwrite by subclasses. This is based on Ruby specification; class variables can be shared on its subclass.
Class variables are similar with global variables. They're too hard to handle safely.
Ruby class variables are not really class variables at all, Apparently they are global to the class hierarchy. Changing a value in the subclass impacts the base classes. Generally speaking, globals and global-like things are bad, they are considered harmful

I'll try to explain problems around class variables in Ruby?

Class variable
You can declare class variables by using @@ for prefix of variable name.

class Share
  # Defining class variable on common
  @@common = :apple
   
  def share
    "Hello, you can have #{@@common}"
  end
   
  def common=(thing)
    @@common = thing
  end
end
 
share_1 = Share.new
puts share_1.share #=> "Hello, you can have apple"
 
share_1 = Share.new
# Share#common method replaces class variable @@common.
share_2.common = :mango
 
# ohh, this effects to other instance of class Share.
puts share_2.share #=> "Hello, you can have mango"


class Share
  @@common = :apple
end
 
# Declare new class Share inherits Fruit
class Share < Fruit
  # You can see superclass' class variable.
  puts @@common #=> :apple
 
  # Try to replace in subclass
  @@common = :mango
end
 
class Share
  # Above line effects to its superclass, Share!
  puts @@common #=> :mango
end

Summary:

Class variables are similar with global variables. They're too hard to handle safely.
For usually cases, I can't recommend to use. Ruby class variables are not really class variables at all, Apparently they are global to the class hierarchy. Changing a value in the subclass impacts the base classes. Generally speaking, globals and global-like things are bad, they are considered harmful

November 21, 2012

Ruby - block, Proc, lambda and method

Here is my brief explanation after reading about ruby closures.

Ruby does great stuffs with closure, like in array iteration we are using closures in everywhere.
Ruby has 4 type of closures - Block, Procs, Lambda and Method. I'm trying to explain them in brief.

Block
It's used with '&' sign prefixed variable also executes using yield or *.call.
1
2
3
4
5
6
7
def do_something_with(&block)
  puts "I did this with block using #{block.call}"
end
 
do_something_with {"ruby"}

#=> I did this with block using ruby

Procs (Procedures)
Its used as other ruby data types (array, hash, string, fixnum etc..), it's reusable and could be used across multiple calls. also several procedures could be passed at a time.
1
2
3
4
5
6
7
def do_something_with(block)
  puts "I did this with Proc using #{block.call}"
end
 
do_something_with Proc.new { "ruby" }
 
#=> I did this with Proc using ruby

Lambda's
It's a procedure (Proc) but with required parameter checking.
Also there is another difference between lambda and Proc. Proc's "return" will stop method and will return from Proc on the other hand lambda‘s "return" will only return it's own value to the caller method.
1
2
3
4
l = lambda {|a, b| ...}
l.call('A')

#=> Error need to pass 2 arguments

Example
1
2
3
4
5
6
7
def who_win_the_title?
  l = Proc.new { return "Rafael Nadal" }
  l.call
  return "Roger Federer"
end
 
#=> "Rafael Nadal"
Because Proc's return is just like method's own return. because it works like reusable code snippet.

Method
Method is another way around in ruby to use existing method as closure.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def cheese
  puts 'cheese'
end
 
def say_cheese(block)
  block.call
end
 
say_cheese method(:cheese)
 
#=> cheese

I learned it from hear - http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

November 14, 2012

Rails On Ubuntu 12.10 Quantal Quetzal

Here's my quick guide to setting up Rails on Ubuntu 12.10 Quantal Quetzal

Step 1: Install Dependencies
The following two commands are going to upgrade any existing packages we have as well as install the dependencies we are going to need to build Ruby properly.

$sudo apt-get -y update && sudo apt-get -y upgrade

$sudo apt-get -y install build-essential zlib1g-dev libssl-dev curl libreadline-dev git-core libcurl4-openssl-dev libyaml-dev python-software-properties 

Step 2: Install Ruby 1.9.3
Grab the latest version of Ruby from ruby-lang.org
The following commands will download the Ruby source, extract it, configure and compile it, and then finally install Bundler.

wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p286.tar.gz
tar -xvzf ruby-1.9.3-p286.tar.gz
cd ruby-1.9.3-p286/
./configure
make
sudo make install
sudo gem install bundler


Step 3: Install Your Database
Choose the database you like.

Install Postgres 9.2

sudo apt-add-repository ppa:pitti/postgresql
sudo apt-get -y update
sudo apt-get -y install postgresql-9.2 libpq-dev

OR

Install MySQL 5.X.XX

sudo apt-get install mysql-server mysql-client libmysqlclient-dev

Step 4: Install Nginx and Passenger
To install Nginx, We will use Passenger's install script. Its simple and straight.

gem install passenger
passenger-install-nginx-module

Just choose the first option (1) to download and install it for you. Accept any defaults it suggests, like installation directories.
After installation is finished, you'll get some configuration tips for Nginx to use Passenger.
Since we are compiling nginx from source, we don't get the start/stop script from Ubuntu's package.
You can get an init script from Linode's website and install it.

wget -O init-deb.sh http://library.linode.com/assets/660-init-deb.sh
sudo mv init-deb.sh /etc/init.d/nginx
sudo chmod +x /etc/init.d/nginx
sudo /usr/sbin/update-rc.d -f nginx defaults

Once that's done, you can start and stop nginx like:

sudo /etc/init.d/nginx start
sudo /etc/init.d/nginx stop

Rails On Ubuntu 12.10

gem install rails

and get started.

October 8, 2012

Adding an nginx init script to auto start in Ubuntu

Assumption

I am assuming you have installed nginx from source using the default options.
If you have used other options or have place the nginx binary in a directory other than /usr/local/sbin/ then you may need to adjust the script shown below.

Stop

If you have nginx running then stop the process using:
sudo kill `cat /usr/local/nginx/logs/nginx.pid`

Init script

The script shown below is from an Ubuntu 10.04LTS install and has been adapted to take into account our custom install of nginx.
Let's go ahead and create the script:
sudo nano /etc/init.d/nginx

Inside the blank file place the following:
#! /bin/sh

### BEGIN INIT INFO
# Provides:          nginx
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the nginx web server
# Description:       starts nginx using start-stop-daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/sbin/nginx
NAME=nginx
DESC=nginx

test -x $DAEMON || exit 0

# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
        . /etc/default/nginx
fi

set -e

case "$1" in
  start)
        echo -n "Starting $DESC: "
        start-stop-daemon --start --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
                --exec $DAEMON -- $DAEMON_OPTS
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon --stop --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
                --exec $DAEMON
        echo "$NAME."
        ;;
  restart|force-reload)
        echo -n "Restarting $DESC: "
        start-stop-daemon --stop --quiet --pidfile \
                /usr/local/nginx/logs/$NAME.pid --exec $DAEMON
        sleep 1
        start-stop-daemon --start --quiet --pidfile \
                /usr/local/nginx/logs/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
        echo "$NAME."
        ;;
  reload)
      echo -n "Reloading $DESC configuration: "
      start-stop-daemon --stop --signal HUP --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
          --exec $DAEMON
      echo "$NAME."
      ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac
exit 0
There's not really the space to go into the workings of the script but suffice to say, it defines where the main nginx binary is located so nginx can be started correctly.
It also defines where to find the nginx.pid file so the process and be correctly stopped and restarted.

Execute

As the init file is a shell script, it needs to have executable permissions.
We set them like so:
sudo chmod +x /etc/init.d/nginx

update-rc

Now we have the base script prepared, we need to add it to the default run levels:
sudo /usr/sbin/update-rc.d -f nginx defaults

The output will be similar to this:
Adding system startup for /etc/init.d/nginx ...
   /etc/rc0.d/K20nginx -&gt; ../init.d/nginx
   /etc/rc1.d/K20nginx -&gt; ../init.d/nginx
   /etc/rc6.d/K20nginx -&gt; ../init.d/nginx
   /etc/rc2.d/S20nginx -&gt; ../init.d/nginx
   /etc/rc3.d/S20nginx -&gt; ../init.d/nginx
   /etc/rc4.d/S20nginx -&gt; ../init.d/nginx
   /etc/rc5.d/S20nginx -&gt; ../init.d/nginx
Done.

Start, Stop and Restart

Now we can start, stop and restart nginx just as with any other service:
sudo /etc/init.d/nginx start
...
sudo /etc/init.d/nginx stop
...
sudo /etc/init.d/nginx restart
The script will also be called on a reboot so nginx will automatically start.

Summary

Adding a process to the run levels like this saves a lot of frustration and effort, not only in manually starting and stopping the process, but it having it automatically start on a reboot.