Install Ruby on Rails in Ubuntu 14.04 LTS

Here is step by step instruction on how to set up ruby on rails in ubuntu 14.04 LTS

Installing Ruby using RVM:

First you have  to install  some dependencies for Ruby.

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev

Now install ruby with RVM using those commends:

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
curl -L | bash -s stable
source ~/.rvm/scripts/rvm
echo "source ~/.rvm/scripts/rvm" >> ~/.bashrc
rvm install 2.1.1
rvm use 2.1.1 --default
ruby -v

Installing Rails:

Rails comes with so many dependencies like NodeJS

To install NodeJS, we’re going to add it using a PPA repository:

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

Now run for install rails:

gem install rails
rails -v
# Rails 4.1.0

Setting Up MySQL:

You can install MySQL server and client from the packages in the Ubuntu repository.

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

Setting Up PostgreSQL:

For PostgreSQL, you need to add a new repository to easily install a recent version of Postgres 9.3.

sudo sh -c "echo 'deb precise-pgdg main' > /etc/apt/sources.list.d/pgdg.list"
wget --quiet -O - | sudo apt-key add -
sudo apt-get update
sudo apt-get install postgresql-common
sudo apt-get install postgresql-9.3 libpq-dev

For postgres you need to set up a user.

sudo -u postgres createuser chris -s
# If you would like to set a password for the user, you can do the following
sudo -u postgres psql
postgres=# \password salayhin

Test your settings for new install:

#### If you want to use MySQL
rails new new_app -d mysql

#### If you want to use Postgres
rails new new_app -d postgresql

# Move into the application directory
cd new_app

# If you setup MySQL or Postgres with a username/password, modify the
# config/database.yml file to contain the username/password that you specified

# Create the database
rake db:create

rails server

All done. Now visit http://localhost:3000 to view your new application.

Enjoy. Happy Coding :)

Add bootstrap to your rails app without gem file

If you want to add Twitter Bootstrap without gem file, follow those steps:

Download Bootstrap
Direct download link Bootstrap 3.0.0
Or got to

Copy CSS Files:

to: app/assets/stylesheets

Copy Js Files:

to: app/assets/javascripts

Append bootstrap CSS to application.css:

Append to: app/assets/stylesheets/application.css
*= require bootstrap

Append bootstrap JS to application.js:

Append to: app/assets/javascripts/application.js
//= require bootstrap

That’s it.

Upgrade to Ruby 2.0.0-x

To upgrade your ruby version follow those steps.

First run the following commands:

rvm get head

followed by:

rvm requirements

If you don’t get any errors you can run:

rvm install 2.0.0-x

To set as your current version of Ruby run the following command:

rvm use 2.0.0-x

To make it the default Ruby:

rvm default 2.0.0-x

Or you can run single command for both use and set default:

rvm use 2.0.0-x --default

Now ruby 2.0.0-x is the default version. To check ruby version run:

ruby -v

and where it’s located executing the command:

which ruby

That’s it. Happy coding :)

Understanding .nil? .empty? .blank? .present? in Ruby on Rails

nil?, empty? and blank? and .present? are confusing for beginner.

Developer needs to be careful in using them and it is better that we understand it well before using it.

Let’s see which method does what.


- It is Ruby method
- It can be used on any object and is true if the object is nil.
- “Only the object nil responds true to nil?” – RailsAPI

In Ruby, all classes inherit from the Object class. nil? is a method of Object; therefore, unless explicitly overridden, all classes have access to nil?. To better understand how Ruby expresses the concept of a non existent object, we need to look at its pseudo-variable nil. The same idea in other languages is often mapped to the primitive type, null or NULL. Depending on the language, NULL may point to nothing at all. Ruby differs here, in that, nil references an actual class called NilClass which exposes methods. This is why it’s possible to do seemingly illogical things like:

=> true

When calling on an object that is non existent, invalid or explicitly set to nil, an instance of the singleton NilClass is returned. A few examples will illustrate how this works.

books = {:physics => "quantam mecanics", :chemistry => "organic chemistry"}

=> nil
=> NilClass
=> true
=> false

test_var = nil
=> true

=> false

=> false

=> false

=> false


Unlike nil?, empty? is only available on some Ruby objects. String, Hash and Array are a few of the classes that implement it. When calling empty? the receiving object is being checked to see if it possesses a non-nil value or values. empty? (at least for the mentioned classes) returns either true or false.

- It is Ruby method
- can be used on strings, arrays and hashes and returns true if:
String length == 0
Array length == 0
Hash length == 0
- Running .empty? on something that is nil will throw a NoMethodError

["physics", "chemistry", "mathmatics"].empty?
=> false

=> false

=> true

=> true

=> true

=> NoMethodError: undefined method `empty?' for 0:Fixnum

test_var2 = nil
= > NoMethodError: undefined method `empty?' for nil:NilClass

The last example above clearly illustrates why one would get unexpected results when trying to do things like this:

dog = {:name => "Beauregard"}
puts "What kind?" if dog[:breed].empty?
=> NoMethodError: undefined method `empty?' for nil:NilClass

# Use nil? instead.
puts "What kind?" if dog[:breed].nil?
=> What kind?


- It is Rails method
- operate on any object as well as work like .empty? on strings, arrays and hashes.
- It also evaluates true on strings which are non-empty but contain only whitespace:

“An object is blank if it‘s false, empty, or a whitespace string.
For example, “”, ” “, nil, [], and {} are blank.”

For instance, I often use blank? when operating on form field values that are considered optional by a model. Going back to the dog hash, we can see how blank? simplifies testing for values.

nil.blank? = true 
[].blank? = true 
{}.blank? = true 
"".blank? = true 
5.blank? == false
dog = {:name => "Beauregard"}
puts "What kind?" if dog[:breed].blank?
=> What kind?

dog = {:name => "Beauregard", :breed => ""}
puts "What kind?" if dog[:breed].blank?
=> What kind?
"  ".blank? == true"  ".empty? == false

Quick tip: !obj.blank? == obj.present?
activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9)

def present? 

Happy Coding :)

Access Rails Development Server From A Different Computer

Sometime you need to access your rails app from a different computer. Here is a trick.

To access your rails app from different computer, you need to run rails app with IP.
While starting the webrick server specify the IP on which your rails application will run (192.168.1.x in your case) using -b option, it binds Rails to the specified IP.

rails server -b 192.168.1.x -p 3000

That’s it. Happy coding :)

URL Shortening on Rails 3 with

For integrating with twitter you need to shorten url. I have used this gem

First add gem to your gemfile

gem bitly

and run

bundle install

Now add this to your controller

require ‘bitly’

philnash’s gem has support for the version 2 and version 3 api. I have use version 3.

Create a new file config\initializers\bitly.rb and write this.

Bitly.configure do |config|
  config.api_version = 3
  config.login = "##############"
  config.api_key = "##################################"

That’s it from installation.

Here is code from controller. This is the example from the gem documentation

u = bitly.shorten('') #=> Bitly::Url

u.long_url #=> ""
u.short_url #=> ""
u.bitly_url #=> ""
u.jmp_url #=> ""
u.user_hash #=> "Ywd1"
u.hash #=> "2V6CFi" #=> a ruby hash of the JSON returned from the API
u.stats #=> a ruby hash of the JSON returned from the API

Based on this your result is expected. if you want the short url try


That’s it. Happy coding :)

Create dynamic sitemap on ruby on rails

What is sitemap:

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

It’s basically a XML file describing all URLs in your page:

The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics.

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="">



























Creating your dynamic sitemap with Ruby on Rails:
First write this on your routes file.

map.sitemap "/sitemap.:format",
     :controller => "home",
     :action => "sitemap",
     :conditions => { :method => :get }

So sitemap URL will be
Now on controller write some method to fetch data.

@posts = Post.all
@categories = Category.all

Now the logic is done and you have to create view for your sitemap to show that sitemap when some request riches

We need to build a XML containing the 3 main nodes to make it a sitemap:

loc – The URL of your page
priority – The priority of the indexing page process between 0 and 1
lasmod – Date of the last modification
changefreq- How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are

  • always
  • hourly
  • daily
  • weekly
  • monthly
  • yearly
  • never

First node is mandatory, the others are optional. Using the XML builder, create the file sitemap.xml.builder to our sitemap and put the next lines:

base_url = "http://#{request.host_with_port}"
xml.instruct! :xml, :version=>'1.0'

xml.tag! 'urlset', "xmlns" => "" do

  xml.url do
    xml.loc "#{base_url}"
    xml.changefreq "monthly"
    xml.priority 1.0

  xml.url do
    xml.loc "#{base_url}/FAQ"
    xml.changefreq "monthly"
    xml.priority 1.0

  xml.url do
    xml.loc "#{base_url}/contact-us"
    xml.changefreq "monthly"
    xml.priority 1.0

  xml.url do
    xml.loc "#{base_url}/about"
    xml.changefreq "monthly"
    xml.priority 1.0

  @categories.each do |category|
    xml.url do
      xml.loc category_url(category)
      xml.priority 0.9

  @posts.each do |post|
    xml.url do
      xml.loc post_url(post)
      xml.lastmod post.updated_at.to_date
      xml.changefreq "always"
      xml.priority 0.9

  @categories.each do |category|
    xml.url do
      xml.loc category_url(category)
      xml.lastmod post.updated_at.to_date
      xml.changefreq "always"
      xml.priority 0.9


That’s it. Happy coding :)

Prevent browser page caching

One of my rails application shows problem about browser caching. After destroying all login session page redirect back me to my home page. But when I click my browser back button I still see the login pages.

Here is few solution for that.

Clear Cache/No-Cache :

// Code disables caching by browser. Hence the back browser button
// grayed out and could not causes the Page_Load event to fire
Response.Cache.SetNoStore(); </pre><p><strong> Use Meta Tag for No-Cache: </strong></p><pre>&lt;meta Http-Equiv="Cache-Control" Content="no-cache"&gt;
&lt;meta Http-Equiv="Pragma" Content="no-cache"&gt;
&lt;meta Http-Equiv="Expires" Content="0"&gt;

Clears Browser History and Redirects URL:

//clears browser history and redirects url
&lt;SCRIPT LANGUAGE="javascript"&gt;
     var Backlen=history.length;
     window.location.href=page url

Rails :

Write this code on application controller.

before_filter :set_cache_buster

  def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"