PigRider Blogs

Sign In
HTML CSS Javascript Ruby on Rails C++ Java Python SQL Git Linux Others All

Basic Ruby on Rails Concepts

[Author: Dingyu]   [Tue, 2013-09-10, 15:29]   [3109 views]

Ruby on Rails

Basic Ruby on Rails Concepts

Why Ruby on Rails ?

1) for fast developing websites 2) DRY Principal(Don’t Repeat Yourself) 3) convention over configuration 4) scaffolding 5) pure Object oriented concepts 6) less coding 7) easy understanding of coding 8) follows MVC architecture 9) using library and gem files

What is MVC and how it Works ?

MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this: Request first comes to the controller, controller finds an appropriate view and interacts with model, model interacts with your database and send the response to controller, then controller based on the response give the output parameter to view.

RESTful Architecture

REST stands for Representational State Transfer. RESTful interface means clean URLs, less code, CRUD interface. CRUD means Create-READ-UPDATE-DESTROY. In REST, they add 2 new verbs, i.e, PUT, DELETE.

Choosing Between belongs_to and has_one ?

If you want to set up a one-to-one relationship between two models, you'll need to add belongs_to to one, and has_one to the other. How do you know which is which? The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
class Supplier < ActiveRecord::Base
  has_one :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
end
The corresponding migration might look like this:
class CreateSuppliers < ActiveRecord::Migration
  def change
    create_table :suppliers do |t|
      t.string  :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.integer :supplier_id
      t.string  :account_number
      t.timestamps
    end
  end
end
Using t.integer :supplier_id makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :supplier instead.

render vs. redirect_to in Ruby on Rails ?

render causes rails to generate a response whose content is provided by rendering one of your templates. Means, it will direct goes to view page. Not like redirect_to, render will keep all current instance variables available in the new rendered view page. redirect_to generates a response that, instead of delivering content to the browser, just tells it to request another url. Means it first checks actions in controller and then goes to view page.

Validations, Callbacks and Observers ?

Validations allow you to ensure that only valid data is stored in your database. Example:
validates_presence_of :user_name, :password
validates_numericality_of :value
We can write custom validation also as
def validate
  errors.add(:price, "should be a positive value") if price.nil? || price < 0.01
end
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state. There are four types of callbacks accepted by the callback macros:
I) Method references (symbol), II) Callback objects, III) Inline methods (using a proc), and IV) Inline eval methods (using a string).
Method references and callback objects are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins), and inline eval methods are deprecated. reference Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, imagine a User model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we should create an observer to contain the code implementing this functionality.
$ rails generate observer User

What is the difference between save and save! ?

Save! performs all validations and callbacks. If any validation returns false, save! throws an error and cancels the save. Save does not throw any error in the case above, but cancels the save. Also, the validations can be bypassed.

Difference between delete and destroy ?

The delete method essentially uses a SQL DELETE statement to delete a row (or an array of rows) from the database directly. Active Record objects are not instantiated, so the object’s callbacks are not executed, including any :dependent association options. The Active Record object is instantiated in the destroy method. Therefore all callbacks and filters are fired off before the object is deleted. This method is less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.

What are filters ?

Filters are methods that run before, after or "around" a controller action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. Filter can take one of three forms: method reference (symbol), external class, or inline method (proc). Types of filters in ruby:
     after_filter
     append_after_filter
     append_around_filter
     append_before_filter
     around_filter
     before_filter
     filter_chain
     prepend_after_filter
     prepend_around_filter
     prepend_before_filter
     skip_after_filter
     skip_before_filter
     skip_filter

What is the flash ?

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. flash is a object of ActionDispatch class.

Difference between Argument and Parameter ?

A parameter represents a value that the method expects you to pass when you call it. An argument represents the value you pass to a method parameter when you call the method. The calling code supplies the arguments when it calls the method. In simple words, parameters appear in method definitions; arguments appear in method calls. For example, in below method, variables param1 and param2 are the parameters
def foo_method(param1, param2):
  .......
end
while calling the method, arg1 and arg2 are the arguments
foo_method(arg1, arg2)

What are the functions performed by Rails migration ?

Rails migration allows the creation of the table and provides the functionality that can be performed on a table with the following commands:
create_table(name, options)
drop_table(name)
rename_table(old_name, new_name)
add_column(table_name, column_name, type, options)
rename_column(table_name, column_name, new_column_name)
change_column(table_name, column_name, type, options)
remove_column(table_name, column_name)
add_index(table_name, column_name, index_type)
remove_index(table_name, column_name)
Rails Migration also allows the use of pre-defined data type in the application as it supports all the data types. The data types consist of string, integer, float, etc. Rails Migration allows the users to use the valid column options like limit (:limit=> "50"), default (:default => "hello"), and null (:null => false implies NOT NULL)

What is the directory structure of Rail ?

The directory structure of Rails includes the following: app/ - this is the folder that consists of controller, models and views of the appliation. config/ - this folder consists of the configuration of the application that consists of runtime rules, routes, databases, etc. db/ - this folder consists the database schema that is being currently used. It also has the information regarding the database migration. doc/ - this is the folder that consists of all the documentation that is required to be used with the application. lib/ - this folder consists of the extended modules and the libraries that is being used by the application log/ - this folder consists of the logs that is being generated during the execution of the application. public/ - this folder consists of the CSS, images and JavaScript folder to be used in the public domain with the application.

What are components used in Rails ?

The components used in Rails are as follows: Action Controller: it is the component that manages all other controllers and process the incoming request to the Rails application. It extracts the parameters and dispatches the response when an action is performed on the application. It provides services like session management, template rendering and redirect management. Action View: it manages the views of the Rails application and it creates the output in both HTML and XML format. It also provides the management of the templates and gives the AJAX support that is being used with the application. Active Record: It provides the base platform for the models and gets used in the Rails application. It provides the database independence, CRUID functionality, search capability and setting the relationship between different models. Action Mailer: It is a framework that provides email services to build the platform on which flexible templates can be implemented.

What is the purpose of load, auto_load, and require_relative in Ruby ?

Load allows the process or a method to be loaded in the memory and it actually processes the execution of the program used in a separate file. It includes the classes, modules, methods and other files that executes in the current scope that is being defined. It performs the inclusion operation and reprocesses the whole code every time the load is being called. require is same as load but it loads code only once on first time. Auto_load: this initiates the method that is in hat file and allows the interpreter to call the method. require_relative: allows the loading to take place of the local folders and files.

Blocks, Procs, and Lambdas

Blocks are Procs that cannot be saved, and as such, are one time use solutions. Procs exist as objects and act like drop-in code snippets. Lambdas have strict argument checking and provide diminutive returns. Blocks
A block is code that is implicitly passed to a method through the use of either curly braces, {...}, or do...end syntax. It’s common convention to use {...} for single line blocks, and do...end for multi-line blocks. For example, the following blocks are functionally the same:
array = [1,2,3,4]
array.map! do |n|
  n * n
end
# => [1, 4, 9, 16]
 
array = [1,2,3,4]  
array.map! { |n| n * n }  
# => [1, 4, 9, 16]
The magic behind a block is the yield keyword; it defers the execution of the calling method in order to evaluate the block. The result of the block, if any, is then evaluated by any remaining code in the method. The yield statement can also accept parameters, which are then passed into and evaluated within the block. Tying this together, a simple example of the map! above method would be the following:
class Array
  def map!
    self.each_with_index do |value, index|
      self[index] = yield(value)
    end
  end
end
This simple representation of map! calls the each_with_index method and replaces the item at the given index with the result of the block. While this is a trivial example of block usage, it helps to show yield's power. The uses of blocks in Ruby are endless, and we frequently use them in our code.
Procs
The above example demonstrates a minor limitation of blocks: they are syntax and disposable. We have to retype blocks every time we reuse them on different arrays, but we can store a block for later use by using the Ruby Proc Object. We can store a Proc in a variable, and then explicitly pass it to any method that accepts a callable object. Rewriting the above example as a Proc would look like the following:
number_squared = Proc.new { |n| n * n }
Let’s modify our map! method to accept and call the Proc object:
class Array
  def map!(proc_object)
    self.each_with_index do |value, index|
      self[index] = proc_object.call(value)
    end
  end
end
 
array = [1,2,3,4]
 
array.map!(number_squared)
 
# => [1, 4, 9, 16]
Take note that we no longer use the yield keyword; instead, we directly use the call method on the Proc object, passing it the value from the array. We receive the same result as before, but we store our block in a variable to reuse a later time.
Lambdas
Lambda function are almost identical to Procs but with two key differences. First, a lambda checks the the number of arguments it receives and returns an ArgumentError if they do not match. For example:
l = lambda { "I'm a lambda" }
l.call
# => "I'm a lambda"
l.call('arg')
# ArgumentError: wrong number of arguments (1 for 0)
Second, lambdas provide diminutive returns – meaning that when a Proc encounters a return statement in it’s execution, it halts the method and returns the provided value. Lambdas on the other hand, return their value to the method, allowing it to continue:
def proc_math
  Proc.new { return 1 + 1 }.call
  return 2 + 2
end
 
def lambda_math
  lambda { return 1 + 1 }.call
  return 2 + 2
end
 
proc_math      # => 2  
lambda_math      # => 4
As you can see proc_math hits the return statement inside the Proc and returns the value of 2. In contrast, lambda_math skips the return statement and evaluates 2 + 2 instead. One final note: Ruby 1.9 introduces the new “stabby” lambda syntax (represented with ->), which is functionally identical to the traditional lambda syntax, but the “stabby” syntax is much cleaner.

The Difference Between Ruby Symbols and Strings

The truth of the matter is that Symbols are Strings, just with an important difference. Strings are mutable, but Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten. Symbols are faster than Strings! Because Strings are mutable, the Ruby interpreter never knows what that String may hold in terms of data. As such, every String (even with the same text) needs to have its own place (and its own object id) in memory. The Ruby interpreter sees that the String will not be used again as it is not assigned to a variable, and marks it for destruction. Symbols of the same text share the same space (and the same object id) on the heap, and they stay in memory throughout the programs operation. Ruby will not mark Symbols for destruction, allowing you to reuse them again and again. In fact, Symbols are not only stored in memory, they are also keep track of via an optimized Symbols dictionary. You can see it by running:
puts Symbol.all_symbols.inspect
Symbols are faster than Strings not only in how they are stored and used, but also in how they are compared. As Symbols of the same text share the same space on the heap, testing for equality is as quick as comparing the object id’s. Testing equality for Strings however, is a bit more computationally expensive. As every String has its own place in memory, the interpreter has to compare the actual data making up the String.

What is unit testing (in classical terms) ?

Unit testing, simply put, is testing methods -- the smallest unit in object-oriented programming. Strong candidates will argue that it allows a developer to flesh out their API before it's consumed by other systems in the application. The primary way to achieve this is to assert that the actual result of the method matches an expected result.

Working with Validation Errors

The errors.add method lets you manually add messages that are related to particular attributes. You can use the errors.full_messages or errors.to_a methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). add receives the name of the attribute you want to add the message to, and the message itself.
class Person < ActiveRecord::Base
  def a_method_used_for_validation_purposes
    errors.add(:name, "cannot contain the characters !@#%*()_-+=")
  end
end

person = Person.create(:name => "!@#")

person.errors[:name]
# => ["cannot contain the characters !@#%*()_-+="]

person.errors.full_messages
# => ["Name cannot contain the characters !@#%*()_-+="]

Does Ruby Support Multiple Inheritance ?

Ruby Supports only Single Inheritance. However, You can achieve Multiple Inheritance through MIXIN concept by including multiple modules in one class. Let us examine the following sample code to gain an understand of MIXIN:
module A
  def a1
  end

  def a2
  end
end

module B
  def b1
  end

  def b2
  end
end

class Sample
  include A
  include B

  def s1
  end
end

samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a MIXIN.

Eager Loading

Eager loading is a way to find objects of a certain class and a number of named associations. This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2.
class Post < ActiveRecord::Base
  belongs_to :author
  has_many   :comments
end
Consider the following loop using the class above:
Post.all.each do |post|
  puts "Post:            " + post.title
  puts "Written by:      " + post.author.name
  puts "Last comment on: " + post.comments.first.created_on
end
To iterate over these one hundred posts, we’ll generate 201 database queries. Let’s first just optimize it for retrieving the author:
Post.includes(:author).each do |post|
This references the name of the belongs_to association that also used the :author symbol. After loading the posts, find will collect the author_id from each one and load all the referenced authors with one query. Doing so will cut down the number of queries from 201 to 102. We can improve upon the situation further by referencing both associations in the finder with:
Post.includes(:author, :comments).each do |post|
This will load all comments with a single query. This reduces the total number of queries to 3. More generally the number of queries will be 1 plus the number of associations named (except if some of the associations are polymorphic belongs_to). To include a deep hierarchy of associations, use a hash:
Post.includes(:author, {comments: {author: :gravatar}}).each do |post|
That’ll grab not only all the comments but all their authors and gravatar pictures. You can mix and match symbols, arrays and hashes in any combination to describe the associations you want to load. All of this power shouldn’t fool you into thinking that you can pull out huge amounts of data with no performance penalty just because you’ve reduced the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it’s no catch-all for performance problems, but it’s a great way to cut down on the number of queries in a situation as the one described above.

has_many :through vs. has_and_belongs_to_many

Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use has_and_belongs_to_many, which allows you to make the association directly:
class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end
The second way to declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model:
class Assembly < ActiveRecord::Base
  has_many :manifests
  has_many :parts, :through => :manifests
end

class Manifest < ActiveRecord::Base
  belongs_to :assembly
  belongs_to :part
end

class Part < ActiveRecord::Base
  has_many :manifests
  has_many :assemblies, :through => :manifests
end
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database). You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.

Polymorphic Associations

A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures Similarly, you can retrieve @product.pictures If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
      t.timestamps
    end
  end
end
This migration can be simplified by using the t.references form:
class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.string :name
      t.references :imageable, :polymorphic => true
      t.timestamps
    end
  end
end

The Law of Demeter

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized in one of the following ways:
  1. Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  2. Each unit should only talk to its friends; don't talk to strangers.
  3. Only talk to your immediate friends.
According to the law of demeter, a model should only talk to its immediate association, don't talk to the association's association and association's property, it is a case of loose coupling. Bad Smell:
class Invoice < ActiveRecord::Base
  belongs_to :user
end
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>
In this example, invoice model calls the association(user)'s property (name, address and cellphone), which violates the law of demeter. We should add some wrapper methods. Refactor:
class Invoice < ActiveRecord::Base
  belongs_to :user
  delegate :name, :address, :cellphone, :to => :user, :prefix => true
end
<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>
Luckily, rails provides a helper method delegate which utilizes the DSL way to generates the wrapper methods. Besides the loose coupling, delegate also prevents the error call method on nil object if you add option :allow_nil => true.

Locking Records for Update

Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates. Active Record provides two locking mechanisms: 1 - Optimistic Locking 2- Pessimistic Locking Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An ActiveRecord::StaleObjectError exception is thrown if that has occurred and the update is ignored. Pessimistic locking uses a locking mechanism provided by the underlying database. Using lock when building a relation obtains an exclusive lock on the selected rows. Relations using lock are usually wrapped inside a transaction for preventing deadlock conditions.

Scopes

Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it. To define a simple scope, we use the scope method inside the class, passing the ARel query that we'd like run when this scope is called:
class Post < ActiveRecord::Base
  scope :published, where(:published => true)
end

# Use this scope
Post.published      # => return the same as Post.where(:published => true)
Just like before, these methods are also chainable:
class Post < ActiveRecord::Base
  scope :published, where(:published => true).joins(:category)
end

Dynamic Finders

For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called first_name on your Client model for example, you get find_by_first_name and find_all_by_first_name for free from Active Record. If you have a locked field on the Client model, you also get find_by_locked and find_all_by_locked methods. You can also use find_last_by_* methods which will find the last record matching your argument. You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like Client.find_by_name!("Ryan") If you want to find both by name and locked, you can chain these finders together by simply typing "and" between the fields. For example, Client.find_by_first_name_and_locked("Ryan", true)

Finding by SQL

If you'd like to use your own SQL to find records in a table you can use find_by_sql. The find_by_sql method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:
Client.find_by_sql("SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER clients.created_at desc")
find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.

pluck

pluck can be used to query a single column from the underlying table of a model. It accepts a column name as argument and returns an array of values of the specified column with the corresponding data type.
Client.where(:active => true).pluck(:id)
# SELECT id FROM clients WHERE active = 1

Client.uniq.pluck(:role)
# SELECT DISTINCT role FROM clients

Single Table Inheritance

Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:
class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end
When you do Firm.create(name: "37signals"), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(name: '37signals').first and it will return a Firm object. If you don’t have a type column defined in your table, single-table inheritance won’t be triggered. In that case, it’ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

Difference between rails 2 and rails 3 ?

8 major Difference between rails 2 and rails 3: 1) New Router API 2) New mailer 3) New Active Record Query interface 4) Assets pipeline 5) Security Improvements 6) Unobtrusive JavaScript (UJS), HTML5 support 7) Dependency management with bundler 8) Gemfile and Gemfile.lock (where all your gem dependencies lies, instead of environment.rb) Click here to see more details on this topic ...

Use of ruby self keyword

There are several important uses, most of which are basically to disambiguate between instance methods, class methods, and variables. First, this is the best way to define class methods:
class Foo
  def self.bar
    "class method bar"
  end

  def bar
    "instance method bar"
  end
end

Foo.bar      # returns "class method bar"

foo = Foo.new
foo.bar      # returns "instance method bar"
Also, within instance methods self refers to the instance, within class methods it refers to the class, and it can always be used to distinguish from local variables.
class Bar
  def self.foo
    "foo!"
  end

  def baz
    "baz!"
  end

  def self.success
    foo
    #looks for variable foo, doesn't find one, looks for class method foo, finds it, returns "foo!"
  end

  def self.fail
    baz
    #looks for variable baz, doesn't find one, looks for class method baz, doesn't find one, raises exception
  end

  def instance_success
    baz
    #looks for variable baz, doesn't find one, looks for instance method baz, finds it, returns "baz!"
  end

  def instance_fail
    foo 
    #looks for variable foo, doesn't find one, looks for instance method foo, doesn't find one, raises exception
  end

  def local_variable
    baz = "is my favorite method"
    baz 
    #looks for variable baz, finds it, returns "is my favorite method"
  end

  def disambiguate
    baz = " is my favorite method"
    self.baz + baz 
    #looks for instance method baz, finds it, looks for local variable baz, finds it, returns "baz! is my favorite method"
  end
end
So, in the end, you can avoid using self in many cases, but it's often helpful to go ahead and use it to make sure that you don't inadvertently create naming conflicts later on. Sometimes those can create bugs that are very hard to find. In the end it's often a matter of personal style.

What is a Ruby Singleton method ?

A method which belongs to a single object rather than to an entire class and other objects. Before explaining about singleton methods I would like to give a small introduction about class methods. What is a class method ? When you write your own class methods you do so by prefacing the method name with the name of the class. There are three ways to write a class method.
  • The first way is to preface the class name with the method name (ClassMethods.method1)
  • The second way is to preface the self keyword with the method name (self.method2)
  • The third way is writing a separate class inside the class which contains the methods (class << self)
Here is an example:
class ClassMethods
  def ClassMethods.method1
    "Hi I am class method prefaced with classname"
  end
 
  def self.method2
    "Hi I am class method prefaced with self keyword "
  end

  class << self
    def method3
      "Hi I am class method inside class withich extends self"
    end
  end
end


p ClassMethods.method1 
# "Hi I am class method prefaced with classname"

p ClassMethods.method2
# "Hi I am class method prefaced with self keyword"

p ClassMethods.method3 
# "Hi I am class method inside a self class"
You can use the similar syntax when creating singleton methods for specific objects. This time you prepend the method name with the name of the object:
firstObj = ClassMethods.new
secondObj = ClassMethods.new
 
def firstObj.singletonMethod
  p "Hi am a singlton method available only for firstObj"
end


firstObj.singletonMethod
# "Hi am a singlton method available only for firstObj"

secondObj.singletonMethod 
# undefined method `singletonMethod' for # (NoMethodError)
This "singletonMethod" belongs only to the firstObj object and won't be available for other objects of this class. If you like to find all the singleton methods for a specific object, you can say objectname.singleton_methods In our case
firstObj.singleton_methods      # => ["singletonMethod"]
secondObj.singleton_methods      # => []

:include vs. :join in Rails

:include and :join both are similar in the way, as because both are use to find the associated table value with single query. For example:
Post.all(:include => :comments)
Post.all(:joins => :comments)
  • :include eager loads associations to avoid the n+1 problem (where one query is executed to retrieve the record and then one per association which is loaded).
  • :joins is for joining association names in a variety of ways and joins the relevant tables.
Similarity:
  • Both :include and :joins are used to get data from 2 or more tables at a time.
  • Both are interchangeable most of the times with some syntactical changes.
  • Both work at any given situation, but best usage depends upon the requirement.
Differences:
:joins
  • We can select the fields to fetch from different tables
  • It will just joins the tables together in sql
  • Its light weight and fast, as we can select the fields and only joins tables
:include
  • We can not select the fields to fetch. Even we try to select, it will just neglect. It will fetch all the fields from all the matching records from included tables
  • It will eager load the associations into memory
  • Its heavy and slow, as it eager loads all the associations into memory
When to use the :include vs. :joins option? Remember these points:
  • :joins does not load the association into memory
  • :include does, it loads each association into memory
  • :include is not compatible with select option
  • use :include when the association is referenced
  • use with :joins, doing a dynamic count on an association or when the association is not referenced

What is web caching and Caching with Rails ?

A web cache is a mechanism for the temporary storage (caching) of web documents, such as HTML pages and images, to reduce bandwidth usage, server load, and perceived lag. So that future requests for that data can be served faster. Rails provides three types of caching techniques by default without the use of any third party plugins.
1) Page caching 2) Action caching 3) Fragment caching
1) Page Caching
Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the file system. To enable page caching, you need to use the caches_page method.
class ProductsController < ActionController

  caches_page :index

  def index
    @products = Products.all
  end

  def create
    expire_page :action => :index
  end

end
By default, the page cache directory is set to Rails.public_path (which is usually set to the public folder) and this can be configured by changing the configuration setting config.action_controller.page_cache_directory In order to expire this page when a new product is added we could extend our example controller like above.
2) Action Caching
One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow (such as pages that need authentication). This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
class ProductsController < ActionController

  before_filter :authenticate
  caches_action :index

  def index
    @products = Product.all
  end

  def create
    expire_action :action => :index
  end

end
You can also use :if (or :unless) to pass a Proc that specifies when the action should be cached. Also, you can use :layout => false to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. Action Caching and Page Caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
3) Fragment Caching
Sometimes you only want to cache a section of a page instead of the entire page. Fragment caching is the answer of this. Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in. As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
<% Order.find_recent.each do |o| %>
  <%= o.buyer.name %> bought <%= o.product.name %>
<% end %>

<% cache do %>
  All available products:
  <% Product.all.each do |p| %>
    <%= link_to p.name, product_url(p) %>
  <% end %>
<% end %>
The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
<% cache(:action => 'recent', :action_suffix => 'all_products') do %>

What is ORM in Rails ?

ORM tends for Object-Relationship-Model. It means that your Classes are mapped to table in the database, Objects are directly mapped to the rows in the table.

What is agile development ?

Agile software development refers to a group of software development methodologies based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams. Advantages
  • Customer satisfaction by rapid, continuous delivery of useful software
  • Working software is delivered frequently (weeks rather than months)
  • Projects are built around motivated individuals, who should be trusted
  • Continuous attention to technical excellence and good design Simplicity
  • Self-organizing teams
  • Regular adaptation to changing circumstances

Difference between Gem and Plugin

GEM
  1. Gem is a packaged ruby application using the packaging system defined by RubyGems.
  2. Rails itself is a Gem
  3. We can install, upgrade and query the gem version.
  4. Gem installed for Ruby interpreter can be used system-wide by that interpreter.
Plugin
  1. Plugin is an extension of Rails Framework.
  2. Can not be upgraded by using a command. To upgrade one have to uninstall and then install upgraded version.
  3. Has to be hooked into rails application. (has to have init.rb)
  4. Have an install.rb file.
  5. Can only be used application wide.

Application Server vs. Web Server

Apache, Nginx, IIS are web servers Mongrel, Webrick, Phusion passenger are application servers Application server is something which works with particular programming language and parses and executes the code. Since Mongrel and Webrick can only work with rails, so they are application servers. Web servers are servers which can take the request from the browser. Web servers normally works on port 80 though we can change the port in configuration. Since Mongrel and Webrick can take that request directly, so they can be thought of as web servers, but web servers do have a lot of other functionality like request pipeline, load balancing etc. Application servers lack these functionalities.

What are helpers in ROR ?

Helpers ("view helpers") are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It's best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.

Resource Routing & the differences between Member Routes and Collection Routes

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code. Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET, POST, PUT and DELETE. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller. For example:
resources :photos
creates seven different routes in your application, all mapping to the Photos controller. You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection. :collection
An action that acts upon a collection of the resource is defined with collection and has a route that reflects that. For example the index action acts upon a collection of the resource:
GET: /posts
:member
An action that acts upon a single instance of a resource is defined with member and has a route that reflects that. The show, create, update and delete actions are examples:
GET: /posts/1
POST: /posts/1
PUT: /posts/1
DELETE: /posts/1
Example of Adding Collection and Member Routes:-
resources :photos do
  get 'preview', :on => :member
  #This will recognize /photos/1/preview with GET, and route to the preview action of PhotosController. 

  get 'search', :on => :collection
  #This will enable Rails to recognize paths such as /photos/search with GET, and route to the search action of PhotosController.
end

What is Rack ?

Rack is a kind of middleware. It sits between your web application and the web server. It handles all of the server-specific API calls, passes on the HTTP request and all the environment parameters in a hash, and gives your application’s response back to the server. In other words, your application doesn’t need to know how to talk to an HTTP server, it needs to know how to talk to Rack. This has a number of advantages. First, talking to Rack is easy. Second, since you only need to know how to talk to Rack, and Rack knows how to talk to many different HTTP servers, your application will run on any of these HTTP servers. Rack is like a universal adapter for web applications.

Difference between attr_accessor and attr_accessible

attr_accessor is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or Model if you wanted, but mostly in your View. attr_accessible allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected which means this field I do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.
All contents in this blog is not written by me originally. I just copied and recorded them from other websites.