Why should i use Ruby on Rails?


Previous yesterday(22 Feb, 2014) we had Delhi NCR Ruby Meetup on Open Source Saturday – How can I contribute to Ruby on Rails?. There i had opportunities to meet few college student, Once of them asked to me – Why should i use Ruby on Rails? Yeah, That’s really good question 🙂 So let’s talk, why should we use Ruby on Rails when dozen of language and frameworks are available.

1. Ruby on Rails provides a consistent approach to build your web applications. If you have already experienced with other web development language or framework, you can understand, how tough it was process, you typically need to survey and ask with expert to choose your various software components to solve the common architectural problems of persistence,  build scripts, testing, logging, database setup, application configuration, web tier components and rest of software life cycle. Using the Ruby on Rails framework these decisions are already made for you, now you can spend more time to understanding software business problem and quickly build a working prototype. By using Rails you become productive in minutes not weeks or months.

2. Ruby on Rails follow CONVENTION OVER CONFIGURATION pragmatic philosophy, this apply in all layers of your software development architecture with the highest productivity gains noticeable in the relationship between the model and the database(ORB- Object Relationship Model). Once the developer understands the rules and constraints, Rails MVC magically connects your view to your controller and model, and your model to the database. That’s awesome .!! You do not have to write any script or tool to manage all this ==> MVC – Model View and Controller.

 

rubyonrails

3. When we talk about OOP’s, Ruby is a fully featured object-oriented language and in addition Ruby come with mix-ins modules which contain independent code to inject into your classes and block. Ruby is an extremely dynamic/run time language, which means that code can be generated and executed on the fly. It’s dynamic nature includes the definition of new classes & methods, as well as the overloading of operators etc. Apart from this you can re-open, redefine and removed existing classes on fly.

4. Unlike other web language and framework, rails has build in templating support, json/xml document and email service.

5. Rails comes with ActiveRecord, Association and ActiveModel(object relationship mapping), which provides seamlessly persisted interface to database like transactions, inheritance, validation, scope and caching.

6. Rails includes support for a variety of web technologies like JavaScript libraries, JQuery, REST, Embedded ruby, HAML, CoffeeScript etc. with configuration in development, test and production environments. If you are planing your application into Web 2.0 space, Rails provides a rich abstracted interface to implementing AJAX operations.

7. Most important rails gives us flexibilities to perform database migration and rollbacks between environments and across development until project at mature stage. However with the Rails framework you will be delighted with the implementation of database migrations for applying and rolling back database changes. You only need to enter your update and rollback scripts in Ruby, framework understands the current version & can move forwards or backwards to any database version.

8. Getting started with Rails is easy as generators/migration will propel you along. DRY(Don’t Repeat Yourself) principle of Rails encourage experience developer to write less code by using the metaprogramming features of Ruby. Overall less code to write means higher productivity, less bugs and minimum complexity.

I hope you convinced, Still doubt? Please go through below links:

http://www.skilledup.com/learn/programming/4-reasons-learn-ruby-first-programming-language/
http://www.techrepublic.com/blog/10-things/10-reasons-why-you-should-learn-ruby-on-rails/3060/
http://blog.teamtreehouse.com/reasons-why-every-web-designer-needs-to-learn-rails

http://articles.businessinsider.com/2011-05-11/tech/30035869_1_ruby-rails-custom-software

Have question? feel free to comment. 🙂

Setting up Unicorn with Nginx on Ruby on Rails


In this blog post, I am going to tell you, How to configure Unicorn web sever on top of Nginx. I Assume that you already installed Ruby and Ruby on Rails on your production OS(operating system) and a sample application working fine.!! If not, follow my previous blog post Setup Ruby On Rails on Ubuntu.

Nginx and Unicorn

To get you started, Let’s install Nginx first by using apt-get package manager.

$ sudo apt-get install nginx

Sometime you get ERROR because your machine packages are not upto date. Run apt-get update to downloads the package lists from the repositories and “updates” them to get information on the newest versions of packages and their dependencies. It will do this for all repositories and PPAs.

$ sudo apt-get update

Once your nignx will install, you command window will prompt:

Setting up nginx-full (1.2.1-2.2ubuntu0.1) ...
Setting up nginx (1.2.1-2.2ubuntu0.1) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
Processing triggers for sgml-base ...
Updating the super catalog...

At this point switch to /etc/nginx/ and /etc/nginx/sites-available configuration directory and have a look to nginx.conf and default respective configuration file. It’s self explanatory under commented in-lines. If still you need more details. I will recommend you to check wiki.nginx for more info.

While the server configuration it’s always better to create separate user(which we have more control over than nobody) for security reasons and increased control by using below command:

$ sudo useradd -s /sbin/nologin -r nginx
$ sudo usermod -a -G web nginx

Starting/stopping/restarting Nginx is pretty straight forward.

$ sudo service nginx start/restart/stop

Now let’s install Unicorn, Unicorn is distributed as ruby gem So you can install vi ruby gem.

$ gem install unicorn

Once Unicorn installed successfully. We need to create two configuration file.

1.Replace /etc/nginx/sites-available/ default file with below code:

upstream shop {
  server unix:/tmp/unicorn.shop.sock fail_timeout=0;
}

server {
   listen 80;# default deferred;
   server_name localhost;
   root /var/www/shop/public;
   try_files $uri/index.html $uri @shop;

location @shop {
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header Host $http_host;
   proxy_redirect off;
   proxy_pass http://shop;
}

error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
   keepalive_timeout 10;
}

2. Create a unicorn.config file in your Rails application configuration file with below code:

working_directory "/var/www/shop"
pid "/var/www/shop/tmp/pids/unicorn.pid"
stderr_path "/var/www/shop/log/unicorn.log"
stdout_path "/var/www/shop/log/unicorn.log"

listen “/tmp/unicorn.shop.sock”
worker_processes 2
timeout 30

You have to tweak a few things to set the right paths in above configuration. Change “/var/www/shop” with your rails application directory.

In my case my Rails application is in /var/www/ with shop name.

Before start your rails application, make sure to include unicorn gem in your Gemfile and run bundle to install all dependencies.

That’s all.

Setup Ruby On Rails on Ubuntu


Installation of Ruby on Rails for Production server is pretty straight forward. Below are the relevant steps.

1.INSTALL THE NEEDED LIBRARIES

sudo apt-get install zlib1g zlib1g-dev build-essential openssl libssl-dev libmysqlclient18 libmysqlclient-dev libyaml-dev

2.DOWNLOAD AND INSTALL RUBY 1.9.3

sudo apt-get update
 sudo apt-get install ruby1.9.3

Note you can install latest Ruby too.

3.INSTALL RAILS

 sudo apt-get install ruby-dev
 sudo apt-get install build-essential g++
 sudo gem install railsconfigure rails application with nginx and unicorn

4.INSTALL SQLITE ADAPTER

 sudo apt-get install libsqlite3-dev

If you passed all above steps without any ERROR, Now it’s time to create a rails demo application OR SCP existing one and test it out.

Below is the steps to create new rails application

 rails new demo
 cd demo
 uncomment therubyracer gem in Gemfile
 sudo apt-get install build-essential g++
 bundle install
 rails g scaffold order name:string
 rake db:create
 rake db:migrate

Open config/routes file and uncomment root ‘welcome/index’ and replaced with ‘orders/index’

$rm -rf public/index

That’s all, Now run your Rails application.

Getting start with Rails3 and Couchrest_model


It’s not difficult to use Couchdb with Rails3. Most of it comes down to making sure that you’re not loading ActiveRecord and understanding how to manager the new Rails dependency.

Installing Couchdb

1. For couchdb, We need install  g++, erlang  and few adapter, so that couchdb will work smoothly.

Run below command form terminal,

$ sudo apt-get install g++
$ sudo apt-get install erlang-base erlang-dev erlang-eunit erlang-nox
$ sudo apt-get install libmozjs185-dev libicu-dev libcurl4-gnutls-dev libtool 

2. One we done with above installation, go to couchdb site and download coach db source file.

In a terminal, go to the folder where you have downloaded the file, extract and go to bin folder and run below commands.

$ ./configure
$ makee
$ sudo make install

That’s it, you done with coachdb installation.

Creating a new Rails Application With couchrest_model

The important thing here is to avoid loading ActiveRecord. So we will use --skip-active-record to skip ActiveRecord initialization.

$rails new cast --skip-active-record

The first thing we need to do is to add the Couchrest_model gem to the Gemfile.

source ‘https://rubygems.org‘ application
gem ‘rails’, ‘3.2.13’
gem ‘couchrest_model’
group :assets do
gem ‘sass-rails’,   ‘~> 3.2.3’
gem ‘coffee-rails’, ‘~> 3.2.1’
gem ‘therubyracer’, :platforms => :ruby
gem ‘uglifier’, ‘>= 1.0.3’
end
gem ‘jquery-rails’

Bundling

Once you’ve configured yeeeour Gemfile, We can then install the gems running the bundle installer:

$ bundle install

Installing couchrest (1.1.3)
Installing couchrest_model (1.1.2)
Using jquery-rails (3.0.4)
Using rails (3.2.13)
Using sass (3.2.9)
Using sass-rails (3.2.6)
Using uglifier (2.1.2)
Your bundle is updated!

Configuring

Once the gems have installed we’ll need to run the Couchdbrest_model configuration generator so that it can create the configuration YAML file.

$rails generate couchrest_model:config

The default file is shown below. We can leave it as it is while we’re developing our application.

config/couchdb.yml

development: &development
   protocol: 'http'
   host: localhost
   port: 5984
   prefix: cast
   suffix: development
   username:
   password:
 test:
   <<: *development
   suffix: test
 production:
   protocol: 'https'
   host: localhost
   port: 5984
   prefix: cast
   suffix: production
   username: root
   password: 123

Everything is in place now for us to begin building our application. We’ll start by creating an User model with email, first_name and last_name fields and use Rails’ scaffolding to create the associated controller and view code.

$rails g scaffold user email:string fname:string lname:string

If we open up the model file we’ll see that it’s a simple class that inherit  CouchRest::Model::Base

class User < CouchRest::Model::Base
 end

you can now start to add properties to the model.

To define a property, simply call the property class method in your model definition:

class User < CouchRest::Model::Base
     property :email, String
     property :fname, String
    property :lname, String
 end

Our application is now ready to run. We don’t need to run any database migrations as CouchDB is schema-less. Now it’s time to run server. Make sure your Couchdb(sudo couchdb) is running in other terminal OR background.

Creating Your First Ruby on Rails Application


Visit blogadda.com to discover Indian blogs

Ruby on Rails First application

Let’s create a basic Ruby on Rails application, without worrying too much about Ruby on Rails basics knowledge. Make sure you have install everything like Ruby, Rails and Mysql as per your Operating System(I am using ubuntu (Linux) you can also install rails on your Windows or Mac machine as well). Now we are going to create our rails application. To begin, open a terminal (Console, command Prompt) and navigate to where you want to create application and type the command:

       $ rails new demo
In above example we used ’demo’ as the name of the application which we will build. As soon as you hit enter, you will see the scripts flow in your terminal creating a bunch of files, These are basic file structure of a Ruby on Rails application.
      ubuntu@ubuntu-Lenovo-G580:~/workspace/RailsApp$ rails new demo -d mysql
      create  
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/assets/images/.keep
      create  app/mailers/.keep
      create  app/models/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep

Now switch to the directory to our application using below command:

       $ cd demo

Now it’s time to take a close look to all the sub-directories and the files inside it to get an idea where the code lives. Once you are done,  Test if your rails application is working by using the command:

      $ rails s

Go ahead and open http://localhost:3000/ in your favorite browser. If you see a page without any Error, then your first rails application works fine.

To start with Mysql integration, we needed to create controller, model and views for our demo application,  which allows us to post your Name, Email and description to Mysql database.

 $ rails g scaffold user name:string email:string desc:text

Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the model, views and controllers for a new resource in a single operation, scaffolding is the tool for this job.

Migrations files are a convenient way to perform CRUD (create, read, update and delete) operation on the database over time in a consistent and easy way. If you haven’t created your database yet we can do it by a command:

 $ rake db:create
At this point, We need to let Rails know about the database configuration information to connect with Mysql. We do this in the file *database.yml*, available in the *app_root_dir/config* subdirectory of Rails Application we created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the host, port, database,
username and password lines to reflect the permissions on the databases you’ve created.
  •       adapter: mysql2
  •       host: <host>
  •       port: <port>
  •       database: <database name>
  •       username: <user_name>
  •       password: ‘<password>’

Rails provides a set of Rake tasks to run certain sets of migrations. As we have recently created a new model for User, a table must be created in our database and requires that we upgrade the database using this command:

$ rake db:migrate

Now lets checkout what we have done so far:

$ rails s

As before, open http://localhost:3000/users in your favorite browser to see your application.

$ rails g scaffold user name:string email:string desc:text

Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the model, views and controllers for a new resource in a single operation, scaffolding is the tool for this job.

Migrations files are a convenient way to perform CRUD (create, read, update and delete) operation on the database over time in a consistent and easy way. If you haven’t created your database yet we can do it by a command:

$ rake db:create
At this point, We need to let Rails know about the database configuration information to connect with Mysql. We do this in the file *database.yml*, available in the *app_root_dir/config* subdirectory of Rails Application we created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the host, port, database,
username and password lines to reflect the permissions on the databases you’ve created.
  •       adapter: mysql2
  •       host: <host>
  •       port: <port>
  •       database: <database name>
  •       username: <user_name>
  •       password: ‘<password>’

Rails provides a set of Rake tasks to run certain sets of migrations. As we have recently created a new model for User, a table must be created in our database and requires that we upgrade the database using this command:

$ rake db:migrate

Now lets checkout what we have done so far:

$ rails s

As before, open http://localhost:3000/users in your favorite browser to see your application.

Rails couchdb demo application


I was trying to create a demo application using couchdb as backend. I faced to many challenges to create demo application.

– couchdb installation on ubuntu 12.10

– Deciding  ORM

– Create demo_app

– configure couchdb.yml file

– Initialize model attributes.

– Access couchdb data from UI interface.

Below are the step by step instruction to fix all above issues and create a demo application.

1.  couchdb installation on ubuntu 12.10

I already blogged Couchdb installation instruction from source code. followed all steps to install couchdb on your ubuntu machine.

2. ORM

I used ‘couchrest_model’ ORM. Install couchrest_model using as ruby gem.

$ sudo gem install couchrest_model

3. Create demo application

$ rails new rails_couchdb –skip-active-record

Add couchrest_model gem in your gemfile.

gem 'couchrest_model'

Do bundle update.

4. configure couchdb.yml file

$ rails generate couchrest_model:config

then create order scaffold.

$rails g scaffold order name:string details:text phone:integer email:string

5. Initialize model attributes.

You need to require couchrest_model in your rails order model.

require 'couchrest_model' 

and add field using properties keyword.

  property :name,      String
  property :details,      String
  property :phone,     Integer, :default => 95556236
  property :email,      String

Now start your rails server, you able to perform CRUD operation on order table.

6. Access couchdb data from UI interface.

Visit http://127.0.0.1:5984/_utils/  to access Couchdb data.

That’s it.

Enjoy….!!!!!!!!

 

 

Passing Blocks in Ruby methods


Today moving around Proc class in Ruby. I come across details about Ruby Blocks and How ruby methods receive block.

There are two way to receive blocks in Ruby methods.

1. Yield

Ruby’s yield statement gives control to a user specified block from the method’s body.

def test
   yield 5,10
   puts "You are in the method test"
   yield 100,200
end

test {|i,j| puts "You are in the block"}

OutPut:

You are in the block
You are in the method test
You are in the block

Even we  can pass parameters with the yield statement.

def test
   yield 5,10
   puts "You are in the method test"
   yield 100,200
end
test {|i,j| puts "You are in the block #{i} and #{j}"}

OutPut:

You are in the block 5 and 10
You are in the method test
You are in the block 100 and 200

2. Proc

If the last argument of a method is preceded by &(Object=Proc.new), then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.

The & calls ‘to_proc’ on the object, and passes it as a block to the method.
In Rails, to_proc is implemented on Symbol, so that these two calls are equivalent:
something {|i| i.foo } and  something(&:foo)

def test(b=Proc.new)   
   b.call(10,20)
   puts "You are in the method test"
   yield 100,200
end
OR
def test(&b)
   p b    
   b.call(10,20)
   puts "You are in the method test"
   yield 100,200
end

test {|i,j| puts "You are in the block #{i} and #{j}"}

Output:

You are in the block 10 and 20
You are in the method test
You are in the block 100 and 200

I hope, it will give sense of how ruby methods call blocks and yield. You can get code from my github Passing-Blocks-in-Ruby-methods.