For creating an rsa key
$ ssh-keygen -t rsa -C “your_email@youremail.com
Author: Abhilash
Installing rails 3.1 and ruby 1.9.2-p180 using rvm and unicorn setup
Install rvm
Open your .bashrc file.
And replace the following line
[ -z “$PS1” ] && return
with
if [[ -n “$PS1” ]]; then
Now add this to the last line of the file
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi
fi
This loads RVM into a shell session.
If already have rvm then
Update rvm
if this shows error like ‘downloaded does not match it’s md5 checksum’
then run
$ rvm reload
$ rvm get latest
For ruby 1.9.2 we want the packages it lists under the MRI & ree section. Let’s install those now.
Setting up Ruby
Do rvm list known to know all ‘Ruby implementation made available through RVM’
Then install latest stable release of ruby
You can see the ruby versions installed and currently using ruby version by
To list default ruby
You can change it by
for default : rvm –default 1.9.2-p180
Using Gemsets
Install rails stable release and then rails 3.1
Start by creating our gemsets
See available gem sets by
If any confusion with rails31 gemset delete it
And create rails31rc
As a best practice, remember to always use one gemset per project*.
Installing Rails
Now we have multiple gem set installed. Now set the different gem set for ruby versions.
Install Rails 3.0.7
Select the gemset for Rails 3.1
for default $ rvm use 1.9.2-p180@rails31rc –default
Install Rails 3.1
if not found
rvmrc file
Switching from one project to another, from a client to a personal project, from testing the release candidate to developing using the latest stable version, always having to manually switch from using a gemset to another can impact productivity. The project .rvmrc files can increase the development speed by setting up our project’s ruby environment when we switch to the project root directory.
The rule of thumb here is to use a .rvmrc file for each project, for both development and deployment.*
.rvmrc file :
if you go to your app folder ‘$ cd myapp’ then you can see like



There are three types of .rvmrc files
1) system : on /etc/rvmrc
2) user : $HOME/.rvmrc
3) Project : .rvmrc
Create a new rails App
with mysql as database
$ rails server -p4000
If u get error like
“”” home/user/.rvm/gems/ruby-1.9.2-p180@rails31rc4/gems/execjs-1.1.2/lib/
execjs/runtimes.rb:43:in `autodetect’: Could not find a JavaScript
runtime. See https://github.com/sstephenson/execjs for a list of
available runtimes. (ExecJS::RuntimeUnavailable) “””
Then you need a javascript engine to run your code…
try installing rubyracer (Embeds the V8 Javascript interpreter into Ruby.)
in your Gemfile add
gem ‘therubyracer’
and do bundle install
Unicorn Installation
$ gem install unicorn
Start unicorn server
A Program for finding all files in a nested folder that contains a specific string : Ruby Vs Python
This program has a major method ‘search in file’ that accepts a folder path as a parameter. Next initialize whatever variables we want.
def search_in_file(folder_path)
@file_array = Array.new
files_has_string = Array.new
erb_files_has_no_string = Array.new
rb_files_has_no_string = Array.new
unknown_files = Array.new
iterate_through_dir(folder_path, @file_array)
———
———
import os
import re
file_array = []
def search_in_file(folder_path):
files_has_string = []
erb_files_no_string = []
rb_files_no_string = []
unknown_files = []
iterate_through_dir(folder_path)
———
———
Then calls a method ‘iterate_through_dir’ which has two parameters in ruby and one in python, ‘folder path’ and instance variable ‘file_array’. In python we initialized a gobal variable ‘file_array’. But in ruby ‘@file_array’ is an instance variable. This method finds file paths of files included in the folder we have given, say ‘sample_folder’. Using the class method ‘glob’ in ruby and os module’s listdir in python we can find all the files and folders that inside sample_folder. Next check it is a file or a folder. If it is a folder we need to iterate through that folder(use recursion ) and get the file paths of files inside the folder. Else it is a file push that file path into our instance array ‘file_array’.
def iterate_through_dir(dir_path, file_array)
file_paths = Dir.glob(dir_path + “/*”)
file_paths.each do |f|
if File.file?(f)
file_array.push(f)
else
iterate_through_dir(f, file_array)
end
end
end
def iterate_through_dir(dir_path):
file_paths = os.listdir(dir_path)
for i in file_paths:
path_to_dir = dir_path + “/” + i
if os.path.isdir(path_to_dir) == True:
iterate_through_dir(path_to_dir)
else:
file_array.append(path_to_dir)
Now we got all the file paths of files inside the nested folder sample_folder in @file_array / file_array. Take each element in the @file_array / file_array, and open that file in read mode. Call ‘f.read’ in ruby and ‘f.read()’ in python to get the file contents as a string.
———
@file_array.each do |file_path|
f = File.open(file_path, ‘r’)
file_contents_in_string = f.read
———
———
———
for i in file_array:
f = open(i, ‘r’)
file_content = f.read()
———
———
Then call ruby-‘.match’, python – ‘re.search'(import regular expression module first -import re) on file content string to find the string inside the file. If you find the string then put it in an array. If you can’t find then put it in an another array. Before that find the file extensions to get the different type of files and append that file paths to different arrays.
———
if (file_contents_in_string[0..500].match(“your string”))
files_has_string << file_path
else
file_extension = File.basename(file_path).split(‘.’)[1]
if file_extension == ‘rb’
rb_files_has_no_string << file_path
elsif file_extension == ‘erb’
erb_files_has_no_string << file_path
else
unknown_files << file_path
end
end
end
———
if re.search(‘find_this_string’, file_content[0:500]):
files_has_string.append(i)
else:
& file_extension = os.path.basename(i).split(‘.’)[1]
& if if file_extension == ‘rb’:
rb_files_no_string.append(i)
elif file_extension == ‘erb’:
erb_files_no_string.append(i)
else:
unknown_files.append(i)
At last call the print_results method to print results.
——–
print_results(@file_array, rb_files_has_no_string, erb_files_has_no_string, unknown_files)
end
print search_in_file(“/your/path/to/nested/folder”)
——–
print_results(rb_files_no_string, erb_files_no_string, unknown_files)
print search_in_file(“/your/path/to/nested/folder”)
Output : Ruby
Output : Python

The method ‘print_results’ accepts four arrays and prints the results accordingly.
Remove duplication from an array in Ruby
If you have an array,
array = [1,2,3,6,3,”A”,3,1,”A”, 5,6,”A”,7,7] then do
array.uniq = [1, 2, 3, 6, “A”, 5, 7]
very easy in ruby right?!!
Cron and Crontab in Linux
- Cron is a daemon that executes scheduled commands in linux.
- Also known as clock daemon.
- This daemon execute so many jobs known as cron jobs.
- This cron jobs are described in crontab files in UNIX systems.
How to add a cron job in crontab files?
- There are almost 7 categories. That are listed below.
- Minute : Add the minute here (eg : 12, 45)
- Hour : Add hour here (eg: 6, 17)
- Day Of month : Add day of month (eg : 10, 25)
- Month : Add month here (eg : 5, Dec, jan)
- Day Of Week : Add day of week (eg : 0=> sunday, 5 => friday)
- User : Add username
- Command : Add Your command here.
- An Example
Open the terminal and type
$ vim /etc/crontab
and add the following line (you can see the time by typing the date command)
50 15 * * * abhi sh /home/abhi/Project/my_project_no1/my_first_cron_job.sh
my my_first_cron_job.sh file contains:
cd /home/abhi/Projects/myProject/ && touch file1.txt file2.txt
Note : Don’t forget to give executable permission to my_first_cron_job.sh file
Here my my_first_cron_job.sh file executes at 15hr 50 min all days and creates two files named file1 and file2 in my /home/abhi/Projects/myProject folder.
# Example of job definition:
# .—————- minute (0 – 59)
# | .————- hour (0 – 23)
# | | .———- day of month (1 – 31)
# | | | .——- month (1 – 12) OR jan,feb,mar,apr …
# | | | | .—- day of week (0 – 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
Note : You can also use * mark that denotes ‘all’. For example If you give 3 * * in day of month, month, day of week respectively ,that means it executes all month 3rd day whatever cron job you given.
Install Rails 3 on Ubuntu 10.04 Lucid Lynx Using RVM with Mysql and sphinx
First install ‘curl’ and ‘git’
- step 1: install curl
$ sudo apt-get install curl - step 2: install git
$ sudo apt-get install git-core - step 3: install rvm
$ bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head ) - step 4: edit .bashrc file to load rvm into the shell session
$ gedit .bashrc
Add the following line to the end of the file:
if [[ -s “$HOME/.rvm/scripts/rvm” ]] ; then source “$HOME/.rvm/scripts/rvm” ; fi - step 5 : restart linux
$ sudo reboot - step 6 : type
$ rvm notes
In the notes RVM tells you what packages you’re gonna need to install for various flavors of Ruby. Since we’re going with 1.9.2 we want the packages it lists under the MRI & ree section. Let’s install those now.
$ sudo aptitude install build-essential bison openssl libreadline5 libreadline-dev curl git-core zlib1g zlib1g-dev libssl-dev vim libsqlite3-0 libsqlite3-dev sqlite3 libreadline-dev libxml2-dev git-core subversion autoconf - step 7 : install ruby 1.9.2 through rvm
$ rvm list known
$ rvm install 1.9.2-head
for 64bit:
$ rvm install 1.9.2 - step 8 : make ruby 1.9.2 as default
$ rvm –default ruby-1.9.2-head
for 64bit:
$ rvm –default ruby-1.9.2
check ruby version
$ ruby -v - step 9 : Install rails 3
$ gem install i18n tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler
$ gem install rails –pre - step 10 : Install database
For Sqlite3
$ sudo apt-get install sqlite3 libsqlite3-dev
$ gem install sqlite3-ruby
(OR)
$ sudo apt-get update
For Mysql goto synaptic package manager and type
mysql-server, mysql-client and install and set password.
Install mysql client libraries :
$ sudo aptitude install libmysqlclient16-dev
or
$ sudo apt-get install libmysql-ruby libmysqlclient-dev - If you want sphinx, install Sphinx
$ wget http://sphinxsearch.com/downloads/sphinx-0.9.8.1.tar.gz
$ tar xzvf sphinx-0.9.8.1.tar.gz
$ cd sphinx-0.9.8.1/
$ ./configure
$ make
$ sudo make install
Then install RVM
Install Ruby 1.9.2
Install Rails 3
Select your database
Install Sphinx
To know about sphinx type
$ search
If you are getting error when starting sphinx make sure that the ‘indexer’,’searchd’,’search’ is under /usr/local/bin or under where sphinx specifies.
You are now ready to go…
HTML parsing using gem Nokogiri in Rails
parsing html is easy using Nokogiri, to do follow the steps
- $ cd yourRailsApp
add the following line to your Gemfile
gem ‘nokogiri’
First install the dependencies$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
For Fedora do
$ sudo yum install libxml2-devel libxslt-devel
For CentOS:
$ sudo yum install -y gcc ruby-devel libxml2 libxml2-devel libxslt libxslt-devel
do bundle install
/yourRailsApp $ bundle install
Your nokogiri installation is completed. Parsing HTML documents look like
doc = Nokogiri::HTML(html_document) and parsing XML documents look like
doc = Nokogiri::XML(xml_document)
Nokogiri converts HTML and XML documents into a tree data structure. Nokogiri extracts data using this tree. Xpath and CSS are small languages used for tree traversal. Xpath is a language that was written to traverse an XML tree struture, but we can use it with HTML tree as well. -
Add a text field in your form
<%= text_field_tag(“my[url]”, @user.url) %> and enter the sample code in this text field. -
@user.url = params[“my”][“url”]
call the function
@user.get_value_from_url
write the function in the model
def get_value_from_url
node = Nokogiri::XML(self.url)
node.xpath(‘//param[@name=”pic”]’).each do |node|
@result = node.attribute(“value”).to_s
end
@result
end
Step 1 : Open the terminal and go to your rails application folder.
Lets try an example take the folowing html code
Step 2 : In views/form.erb add
Step 3 : In controller add
Then you get the value : “http://www.my_site.com/v/xedFamzsaaxo7hc0?fs=1&hl=en_US” in the result. Look its so easy to use nokogiri. Its Wonderful !!
You can also view Aaron Patterson’s (creator of Nokogiri) blog from here.
PDF Generation with Wicked pdf in Rails
I am using ruby 1.9.2 and rails 3. I think Wicked pdf is better than other rails pdf generation plugins. To start with wicked follow the steps :
- $ cd /home/MyApp
Install wkhtmltopdf first .Open gem file, and add the line
gem ‘wkhtmltopdf’
$ bundle install
Wicked pdf is using the wkhtmltopdf to create a pdf document from a rails html template.
With wicked pdf we can,- Define documents structure through a simple html document.
- Theme them through CSS
Just Download the static complied version from wkhtmltopdf home page. Extract it and place it under /usr/local/bin.
Note : If your system is 64-bit download the 64Bit version. Else you get error, Something like ‘Exec Error’,’Executable format error’, etc.
Step 1: Open the terminal and go to your rails application folder.
- $ rails plugin install git://github.com/mileszs/wicked_pdf.git
now a configuration file is needed, we can use plugins generator script for it . But in rails 3 it will not work. Just copy the wicked_pdf.rb to initializers.
$ cp vendor/plugins/wicked_pdf/lib/wicked_pdf.rb config/initializers
and add the following to the config/initializers/wicked_pdf.rb
WICKED_PDF = {
:exe_path => ‘/usr/local/bin’
}
Step 2: Install wicked pdf plugin
- In my rails app I created an action index_pdf. Under the action put the following line.
def index_pdf
render :pdf => “my_pdf”,:layout => false,:template => ‘/users/index_pdf’,:footer => {:center =>
“Center”, :left => “Left”, :right => “Right”}
end
The render :pdf call has a lot of options. you can use these.
Step 3:Add pdf instructions to your controller.
- Put the link in your app, in your home page or somewhere.
<%= link_to ‘Create PDF document’, index_pdf_path(@user, :format => :pdf) %>
the index_pdf_path is the path I mentioned in the route.rb file,
match “/download_pdf(.:format)” => “users#index_pdf”, :method => :get, :as=>:index_pdf
When all are set click the link to download the pdf.
Step 4: Create a view file in app/view/index_pdf.erb
-
Include image in Wicked pdf
write a function in application helper to take your images in wicked pdf.
def pdf_image_tag(image, options = {})
options[:src] = File.expand_path(RAILS_ROOT) + ‘/public/images’ + image
tag(:img, options)
end
Add your image in public/images.
Write the following code in view <%= pdf_image_tag(‘photo.png’, :style=>”margin:0px;padding:0px”,:width=>”160″, :height=>”160″)%>
Its ‘wicked!!’ isn’t it?
Wifi no longer working on ubuntu 10.04 (Lucid)
Here describing the steps that taken by me to get the wireless connection right on my Ubuntu 10.04
After installing ubuntu 10.04, check the wireless network is enabled.
Open the terminal and type the following commands.
$ sudo su
# ifconfig
# mii-tool -A 10baseT-FD eth0
Restart your system. It will work.
If not, activate broadcom STA wireless driver in your ubuntu by going to System > Administration > Hardware drivers . Select ‘Broadcom STA’ driver and click on the activate button. Restart your system. It will work. If your system has no such driver then install it by going to System > Administration > Synaptic Package Manager. Enter root password. Type ‘broadcom’ in Quick search. Right click on broadcom-sta-common and mark for install. Then click apply.
If your system is not showing any drivers in Hardware drivers, and showing ‘No proprietary drivers are use on this system.’ then uninstall the broadcom-sta driver and bcmwl-modalises and install it again. Restart the system. It will work.
Again if it’s not working download the package rt3090-dkms_2.3.1.3-0ubuntu0~ppa1_all from here. Now install the package by double-clicking the package. Restart the system. It will be Ok.
Storing a simple student database in Rails
Set up Ruby on Rails from http://rubyonrails.org/download. Make a directory ‘my_rails’ in your home folder for rails applications.
$ cd my_rails
create your application as following
$ rails new student_db
$ cd student_db
For including gems, you need to update the Gemfile, that resides in your application folder. Open the ‘Gemfile’ and update.
Gemfile :
source ‘http://rubygems.org’
gem ‘rails’, ‘3.0.0’
gem ‘sqlite3-ruby’, ‘1.2.5’, :require => ‘sqlite3’
Specify the version number for sqlite3. This is for avoiding confusion while installing the gems.
Install gems
$ bundle install
Now you are ready to generate the student model. Use scaffold generator.

Note : Rails developers dislike scaffold. Because it itself generates code. So don’t use it. This is only for referring the application.
$ rails generate scaffold Student first_name:string last_name:string roll_no:integer total_mark:integer
Migrate the database using rake.
$ rake db:migrate
Now run the server.
$ rails s
open the browser and go to http://localhost:3000/student
To see this application visit,
Student_data_base
