Tuesday, July 24, 2012

Advance Rails Questions


"YOU MUST BE ENJOYING TO KNOW THESE FACTS/ANSWERS" 

Threads in rails:-

Ruby/rails support single level threading not Multi-threading. 
Multi-threading occurs when multiples thread are executed in parallel,only one request is handled at a time. As such a standard rails app is single threaded. You can however spawn new threads within a request that would make your app multi threaded, most people never encounter this.
If you are having issues use below lines

require 'thread'  
Thread.exclusive do # stuff here end
What is Difference between “Extend” and “Include” ?
“extend" adds methods from a module into a class as class methods.(ClassName.method)
"include" adds methods from a module into a class as instance methods.(ClassName.new.method)
It is quite easy to demonstrate this actually. 

   module SomeModule 
    def hi 
        puts "hello" 
     end 
   end 
  class ExtendSample 
    extend SomeModule 
  end
  ExtendSample.hi 
  class IncludeSample 
    include SomeModule 
  end 
  IncludeSample.new.hi

What is SCOPE in rails? 

  Class Shirt < ActiveRecord::Base   
  scope :red, where(:color => 'red') 
  scope : dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) end
  Called => Shirt.red  (here complex conditions are defined into an scope and can be used as class method)


What is Action Pack ?
 
The controller supplies data to the view, and the controller receives events from the pages generated by the views. Because of these interactions, support for views and controllers in Rails is bundled into a single component,Action Pack.

What is Active Record?
 
Active Record is the ORM layer supplied with Rails. It closely follows the stan-
dard ORM model: tables map to classes, rows to objects, and columns to object attributes. It differs from most other ORM libraries in the way it is configured.By relying on convention and starting with sensible defaults, Active Record minimizes the amount of configuration that developers perform.

The most common templating scheme, called Embedded Ruby (Erb),

RJS views: - These allow you to create JavaScript fragments on the server that are then executed on the browser. This is great for creating dynamic Ajax interfaces

Define Controllers in Rails ? 
 
The controller is also home to a number of important ancillary services:
• It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well.
• It manages caching, which can give applications orders-of-magnitude performance boosts.• It manages helper modules, which extend the capabilities of the view
templates without bulking up their code.
• It manages sessions, giving users the impression of ongoing interaction with our applications.


Ruby Is an Object-Oriented Language?
Everything you manipulate in Ruby is an object, and the results of those manipulations are themselves objects.

An object is a combination of state (for example, the quantity and the product id) and methods that use that state (perhaps a method to calculate the line item’s total cost).


Regular Expressions in Rails!
A regular expression lets you specify a pattern of characters to be matched in a string.
Programs
typically test strings against regular expressions using the =~ match operator:
       if line =~ /P(erl|ython)/
 puts "There seems to be another scripting language here"
end


What is Blocks and Iterators ?

Code blocks are just chunks of code between braces or between do...end. A common convention is that people use braces for single-line blocks and do/end  for multiline blocks:
A method can invoke an associated block one or more times using the Ruby  yield statement.


animals = %w( ant bee cat dog elk ) # create an array
animals.each {|animal| puts animal } # iterate over the contents

Each integer N implements a times method, which invokes an associated block
N times:
3.times { print "Ho! " } #=> Ho! Ho! Ho!
The & prefix operator will allow a method to capture a passed block as a named parameter.
def wrap &b
  print "Santa says: "
  3.times(&b)
  print "\n"
end
wrap { print "Ho! " }


Within a block, or a method, control is sequential except when there is an exception.



Exception:-

Exceptions are objects (of class Exception or its subclasses). The raise method causes an exception to be raised. This interrupts the normal flow through the code. Instead, Ruby searches back through the call stack for code that says it can handle this exception.

begin
    content = load_blog_data(file_name)
rescue BlogDataNotFound
    STDERR.puts "File #{file_name} not found"
rescue BlogDataFormatError
   STDERR.puts "Invalid blog data in #{file_name}"
rescue Exception => exc
   STDERR.puts "General error loading #{file_name}: #{exc.message}"
end



Ruby Structure:
There are two basis structure: classes  and modules.


Line 1
 class Order < ActiveRecord::Base
    has_many :line_items
    def self.find_all_unpaid
     self.where('paid = 0')
    end

  def total
     sum = 0
     line_items.each {|li| sum += li.total}
   end
end

What is Class ?


Class definitions start with the keyword class followed by the class name (which must start with an uppercase letter). This Order class is defined to be a sub-class of the class Base within the ActiveRecord module.


What is Modules ?

Modules are similar to classes in that they hold a collection of methods, con-stants, and other module and class definitions. Unlike classes, you cannot create objects based on modules.
Modules serve two purposes. First, they act as a namespace, letting you define methods whose names will not clash with those defined elsewhere. Second, they allow you to share functionality between classes—if a class mixes in a module, that module’s instance methods become available as if they had been defined in the class. Multiple classes can mix in the same module, sharing the module’s functionality without using inheritance. You can also mix multiple modules into a single class.
YAML
YAML1 is a recursive acronym that stands for YAML Ain’t Markup Language. In the context of Rails, YAML is used as a convenient way to define configuration of things such as databases, test data, and translations. Here is an example:
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000

Marshaling Objects

Ruby can take an object and convert it into a stream of bytes that can be stored outside the application. This process is called marshaling. This saved object can later be read by another instance of the application (or by a totally separate application), and a copy of the originally saved object can be reconstituted.

There are two potential issues when you use marshaling. First, some objects cannot be dumped. If the objects to be dumped include bindings, procedure or method objects, instances of class IO, or singleton objects, or if you try to dump anonymous classes or modules, a TypeError will be raised. Second, when you load a marshaled object, Ruby needs to know the definition of the class of that object (and of all the objects it contains).

empty ! OR empty ?

Bang methods normally do something destructive to the receiver. Predicate methods return true or false depending on some condition.
So, count ||= 0 gives count the value 0 if count doesn’t already have a value.


count ||= 0 # count = count || 0
obj = self.new


Using self.new instead returns a new object of the receiver’s class, of subclass as well

Lambda
The lambda operator converts a block into an object of type Proc.

Require:-
require File.dirname(__FILE__) + ’/../test_helper’
Ruby’s require method loads an external source file into our application.
This is used to include library code and classes that our application relies on. In normal use, Ruby finds these files by searching in a list of direc-tories, the LOAD_PATH.


What is "send" method in rails?

send(symbol [, args...]) → obj
__send__(symbol [, args...]) → obj
Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
It add methods in runtime .

  class Klass 
    def hello(*args)
     "Hello " + args.join(' ') 
    end
   end
   k = Klass.new k.send :hello, "gentle", "readers" #=> "Hello gentle readers"


Rails Caching

1. Rails default cache:: Page Caching:
Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver
    caches_page :index

2. Action Caching
One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. 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. Clearing the cache works in the exact same way as with Page Caching.

caches_action :index
NOTE::1. Page caching ignores all parameters. For example /products?page=1 will be written out to the filesystem as products.html with no reference to the page parameter. Thus, if someone requests /products?page=2 later, they will get the cached first page. Be careful when page caching GET parameters in the URL!


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
Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.


 For All available products: 
    <% cache(:action => 'recent', :action_suffix => 'all_products') do %>
 To expire fragement:

    <% expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products') %>

 4. Sweepers
 Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code. It does this by moving all the work required to expire cached content into an ActionController::Caching::Sweeper subclass. This class is an observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.

class ProductSweeper < ActionController::Caching::Sweeper
observe Product # This sweeper is going to keep an eye on the Product model
# If our sweeper detects that a Product was created call this
def after_create(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
private
def expire_cache_for(product)
# Expire the index page now that we added a new product
expire_page(:controller => 'products', :action => 'index')
# Expire a fragment
expire_fragment('all_available_products')
end
end
host: 10.179.101.110
username: ngforms
password: 12expe89
socket: /var/lib/mysql/mysql.sock 
SQL Caching
Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.

Cache Stores

Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.

You can set up your application’s default cache store by calling config.cache_store= in the Application definition inside your config/application.rb file or in an Application.configure block in an environment specific configuration file (i.e. config/environments/*.rb). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.


config.cache_store = :memory_store

Alternatively, you can call ActionController::Base.cache_store outside of a configuration block.
You can access the cache by calling Rails.cache.


RACK



Migrations

rails generate migration AddPartNumberToProducts
rake db:migrate VERSION=20080906120000
rake db:rollback STEP=3
(will run the down method from the last 3 migrations.)
$ rake db:migrate:redo STEP=3
rake db:migrate:up VERSION=20080906120000

Active Record provides methods that perform common data definition tasks in a database independent way (you’ll read about them in detail later):
  • create_table
  • change_table
  • drop_table
  • add_column
  • change_column
  • rename_column
  • remove_column
  • add_index
  • remove_index

Active Record supports the following types:
  • :primary_key
  • :string
  • :text
  • :integer
  • :float
  • :decimal
  • :datetime
  • :timestamp
  • :time
  • :date
  • :binary
  • :boolean

will append ENGINE=BLACKHOLE to the SQL statement used to create the table (when using MySQL the default is ENGINE=InnoDB).

Observers


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 outside of a model. For example, it could be argued that a User model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn’t directly related to your model, you may want to consider creating an observer instead.

rails generate observer User

class UserObserver < ActiveRecord::Observer
def after_create(model)
# code to send confirmation email...
end
end

As with callback classes, the observer’s methods receive the observed model as a parameter.

Observers are conventionally placed inside of your app/models directory and registered in your application’s config/application.rb file. For example, the UserObserver above would be saved as app/models/user_observer.rb and registered in config/application.rb this way:

# Activate observers that should always be running
config.active_record.observers = :user_observer


Transaction Callbacks
There are two additional callbacks that are triggered by the completion of a database transaction: after_commit and after_rollbac


What is Fingerprinting and Why Should I Care?

Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated are altered to be unique to the content contained in the file.
When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as cache busting.







Cheers!!
Manish Shrivastava,
Ruby On Rails Developer, India.