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. 🙂

Advertisements

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.

Install camping on Ubuntu


Camping:

– Camping is a web framework which consistently stays at less than 4kB of code. You can probably view the complete source code on a single page. But, you know, it’s so small that, if you think about it, what can it really do?

Camping is a Ruby Micro Framework

The idea here is to store a complete fledgling web application in a single file like many small CGIs. But to organize it as a Model-View-Controller application like Rails does. You can then easily move it to Rails once you’ve got it going.

Installation:

– Camping is distributed as ruby gem, So we can install in single command.

$ gem install camping

– For full package we recommend to install camping-omnibus which contain all required libraries.

gem install camping-omnibus

If you are going to use the views you also need to install markaby,


$ gem install markaby

That's it. Now you can enjoy camping on your ubuntu.  

Manual active record db connection


Guy’s quick tour, how to connect standalone ruby file to mysql datababase. You can follow steps to understand procedure OR clone my working sample example active recored connection

1. Install relevant gems.
sudo gem install activerecord
sudo gem install yaml_db
sudo gem install logger

2. Create a ruby file and add below code.

require ‘rubygems’
require ‘active_record’

ActiveRecord::Base.establish_connection(
:adapter => ‘mysql’,
:database => ‘test’,
:username => ‘root’,
:password => ”,
:host => ‘localhost’)

when we run this file from rails console it should run without any error and output.

3. Now create table LOCATIONS in test database and insert some row.

mysql> create table locations(name varchar(100), city varchar(100));
Query OK, 0 rows affected (0.60 sec)

mysql> show tables;
+—————-+
| Tables_in_test |
+—————-+
| locations |
+—————-+
1 row in set (0.28 sec)

mysql> insert into locations(name,city) values(‘Sanyam’,’Bettiah’);
Query OK, 1 row affected (0.12 sec)

mysql> insert into locations(name,city) values(‘Sanyam’,’Bettiah’);
Query OK, 1 row affected (0.21 sec)

mysql> select * from locations;
+——–+———+
| name | city |
+——–+———+
| Ankit | Asansol |
| Sanyam | Bettiah |
+——–+———+
2 rows in set (0.00 sec)

4. Add ruby class and inherit ActiveRecord::Base, So we can perform database operation.

class Location < ActiveRecord::Base
end

5. Add initialize action to access database and execute some command.

class Location < ActiveRecord::Base

def initialize
p 'Tables details'
p Location

p 'Count no of rows in table'
p Location.count
end

end

Location.new

6. Run ruby file from command line, it supposed to display

pravinmishra@ubuntu:~/workSpace/RUBY_CODE/active_record_connection/lib$ ruby main.rb
“Tables details”
Location(name: string, city: string)
“Count no of rows in table”
2

that’s it.

Addition we can separate data configuration in different file and add logger to display sql query OR errors if any. I did all this two setups in active recored connection , You can take a look. 🙂

Cheers!!

current_page?


Sometimes we come to scenario, we need to find out what the current page is. The best I could do was this:

1. current_page?(options)

Will return true if the current request URI was generated by the given options.
Let’s say we’re in the /shop/checkout?order=desc action.
current_page?(:action => ‘process’)
# => false

current_page?(:controller => ‘shop’, :action => ‘checkout’)
# => true

2. request.path_parameters

this should return a hash along the controller and action.
{:action => ‘my_action’, :controller => ‘my_controller’}

Thanks

ruby script for reading the contents of a file and appending in othere file


Content of text file
readdata.txt

Hi, This is Pravin Mishra
Ruby on rails developer
From India

and generating some output based on the content:

readfile.rb


class ReadFile
 
  def execute
    file = File.open(“readdata.txt”)
    contents = []
    all_data = Hash.new
    file.each {|line|
        tokens = line.split(” “)
       
        if tokens.count > 1
            tokens.each_with_index do |data, index|
              all_data[index] = data
            end
            contents << all_data
            all_data = Hash.new
        end
        
        my_file = File.new(“new_file.txt”, “w”)
        my_file.puts contents
    }

  end
 
end

if __FILE__ == $0
  sql = ReadFile.new
  sql.execute
end

Run from the command line as:

> ruby readfile.rb

Out put would be
{0=>”Hi,”, 1=>”This”, 2=>”is”, 3=>”Pravin”, 4=>”Mishra”}
{0=>”Ruby”, 1=>”on”, 2=>”rails”, 3=>”developer”}
{0=>”From”, 1=>”India”}
in new_file.txt

that’s it…!!!