breaking into the unknown…

Leave a comment

what are the components of rails ?

rails is responsible for popularity of ruby to a great extent. Rails 4.2.1 is out and it summarizes itself with below line, each words are true to itself.

Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.

As rails is maturing , it is refactoring and restructuring itself. some of the features are removed from core rails library and build into separate gem, which you can include or exclude as per your needs. For example, observers are part of ActiveRecord before 4.0 but after that it is moved to separate gem rails-observer .

Note that rails is gem in itself . It has structured itself in different modules or component , each providing a specific functionality. When you create a new rails application with command below:

$ rails new demoapp

By default all the components get loaded due to below line of code in config/application.rb file

require File.expand_path('../boot', __FILE__)

require 'rails/all'


module Demoapp
  class Application < Rails::Application
   ----more code ...

You are using require ‘rails/all’ , which ask rails to load all the components. Read here about rails booting and loading. But it is unnecessary to load all the components if you do not need it. say your application do not need to send any email, so it is better to not load ActionMailer component or module. Remember that, heavy your application is , more time it will take to load, so keep unwanted thing out.

Well for this you must know what are the components and what it do for you. Below goes the list :

=> ActionMailer :

It manage email support for rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.

=> ActionPack :

It is responsible for mapping the incoming request i,e URL to a controller action and then rendering the corresponding  view. Internally, it is using rack to communicate with the server. It also manage view caching

=>ActionView :

It is responsible for rendering the view . You may not need it if you expose service as an API rather then a interface .The view rendering is done through external gems like erubis for .erb which is the default(you do not install it but get installed as rails dependency. you will see it if you do gem list on your console) or say haml for .haml templates.

=>ActiveJob :

Active Job is a framework for declaring jobs and making them run on a variety of queueing backends. The basic idea is to provide support for creating job to be run later, which can be then handled with other gem build over it. So to say ActiveJob will provide to infrastructure to create the job, which can be then handled by any of the gem sidekiq or resque or delayed job etc .

=>ActiveModel :

They are responsible for model name introspections, conversions, translations and validations . Basically ActiveModel implementations are ORMs (see ActiveRecord, below), but they can also use non-relational storage like MongoDB, Redis, Memcached or even just local machine memory.

 =>ActiveRecord :

They are responsible to map your model with your ORM database. Remember when you do, the user detail directly get saved in users table.this mapping is getting handled with ActiveRecord. You do not need it if your model do not interact with database . all the callbacks like before_save etc and associations between model are covered under it.

=>ActiveSupport :

ActiveSupport is a compatibility library including methods that aren’t necessarily specific to Rails. You’ll see ActiveSupport used by non-Rails libraries because it contains such a lot of useful baseline functionality. ActiveSupport includes methods like how Rails changes words from single to plural, or CamelCase to snake_case. It also includes significantly better time and date support than the Ruby standard library.

=>Bundler :

Bundler manages an application’s dependencies through its entire life, across many machines, systematically and repeatably. It is responsible to manage all your gem dependency .

=>Railities :

Railties is responsible for gluing all frameworks together. Overall, it:

->handles the bootstrapping process for a Rails application
->manages the rails command line interface;
->and provides the Rails generators core.

=>sprockets-rails :

 It use to manage your assets pipeline introduced since rails 3.1. Initially it was a core feature of rails but has moved into separate gem sprockets-rails since rails 4.0, so that it can be refactored and develop independently . If you have used it with before rails 4, you have observed the log containing details of all the assets requested which is annoying. but after rails 4.0 when it is moved as separate gem, The configuration option config.assets.logger has been removed. Sprockets will no longer pollute your logs when assets are compiled. Nevertheless, Action Pack will continue to log when assets are requested from your server if they are not precompiled. Also there is increase in performance, now assetes get compiled in about 2 second rather then 8 to 10 second

=> Gems:

They are independent library, which you keep adding as per your need.



how rails boot : order of config files loading

Thinking on it for long, but only today get time to delve into it. Have you ever get curious of what going under the hood when you start the rails server, how your rails application get booted, when your gem gets loaded and config files get executed. Well there goes a lot of thing between you type rails s on your project folder from terminal and go to localhost:3000 in your browser.

I tried to see it myself. To get the basic idea I gone through rails doc on initialization . It is quite elaborative make me lost in the details. So I figure out my own way to get the sense of things : “I use puts statement in all the important files, relevant as per the rails doc”

Below is the output on console when I started the server (I am using rails 4.1.9):

$ rails server
	Iam in Gemfile
	Iam in config/boot.rb
	Iam in config/application.rb
	=> Booting Puma
	=> Rails 4.1.5 application starting in development on
	=> Run `rails server -h` for more startup options
	=> Notice: server is listening on all interfaces (
	=> Ctrl-C to shutdown server
	Iam in config/environments/development.rb
	Iam in config/initializer folder
        Iam in config/routes.rb
	Iam in config/environment.rb
	Iam in
	Puma 2.8.2 starting...
	* Min threads: 0, max threads: 16
	* Environment: development
	* Listening on tcp://


So, now you can see the order in which the files is getting loaded are as below:

Gemfile   -> boot.rb    ->  config/application.rb   -> basic server message get printed  -> config/environments/development.rb  ->  files in initializer foler  ->  config/routes.rb  ->  config/environment.rb  ->

Now lets see, how and from where they are getting loaded at the code level .

Step 1: Starting the Server

The story begin when you start the server with the below command

$rails server

any command which run from terminal is a executable, residing in one of the folder in load path of your system. You can see it with below command:


all the location separated by : is searched by your system to run any command you type on terminal, So it means rails executable (rails executable get installed when you install a rails gem) must be present in any one of these position.

But wait, what the second argument server is for ?  well it is argument to command rails . You can run without it

$ rails
Iam in Gemfile
Iam in Gemfile
Iam in boot.rb
Usage: rails COMMAND [ARGS]

The most common rails commands are:
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 dbconsole   Start a console for the database specified in config/database.yml
             (short-cut alias: "db")
 new         Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"

So you can see that rails command still run without the server option, but it give you message how to use it properly.

O.K, lets find what code the rails executable have. It may be present in any of folder within the path above. search each of themfor rails . You will get it in bin. Open with nano command to see its content

$ nano bin/rails

#!/usr/bin/env ruby
  load File.expand_path("../spring", __FILE__)
rescue LoadError
APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'

So the code here first try to load a file spring, which basically have the code to load the gems as below:

$ nano bin/spring

#!/usr/bin/env ruby

unless defined?(Spring)
  require "rubygems"
  require "bundler"

  if match =^GEM$.*?^    spring \((.*?)\)$.*?^$/m)
    ENV["GEM_PATH"] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR)
    ENV["GEM_HOME"] = ""
    Gem.paths = ENV

    gem "spring", match[1]
    require "spring/binstub"

The remaining line of rails executable will craete a constant variable holding path of application.rb, load the boot file and the last line will load the commands file(located in installed rails gem at rails/railties/lib/rails/commands.rb )

So till now, you get to know, how the rails server start, why Gemfile are loaded first, followed by boot.rb file.

So we have understand upto :  Gemfile  -> boot.rb


Step 2:  Insight into boot.rb file:

We will look into boot.rb file and see how it influence the remaining order of things. It has below line of code

# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)

require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])

So boot.rb file do not have any other influence on the remaining sequence of things. It just install all your gems and done with its role


Step 3: Insight into way application.rb is loaded

we have noticed that the last line in rake executable is require ‘rails/commands’ , it basically load the file  rails/railties/lib/rails/commands.rb . It has below content

ARGV << '--help' if ARGV.empty? 
aliases = {   "g"  => "generate",
  "d"  => "destroy",
  "c"  => "console",
  "s"  => "server",
  "db" => "dbconsole",
  "r"  => "runner",
  "t"  => "test",

command = ARGV.shift
command = aliases[command] || command

require 'rails/commands/commands_tasks'!(command)

So you can see that, the above code creating aliase for different commands. now you know how you can use rails s also in place of rails server .

The last two line is important. It load command_task.rb file at(rails/railties/lib/rails/commands/commands_tasks.rb) and the last line run the command you passed i,e for server command , it becomes"server").run_command!(command)

basically the above line execute below line of code from the file rails/railties/lib/rails/commands/commands_tasks.rb

  def server
      require_command!("server") do |server|
        # We need to require application after the server sets environment,
        # otherwise the --environment option given to the server won't propagate.
        require APP_PATH

from here you can see that APP_PATH which store the application.rb file get loaded and the the server get started.

So upto now, you should have clarity on below sequence of flow

rails server -> Gemfile loaded -> boot.rb loaded -> application.rb loaded


Step 4: insight into server.start

in the above code after config/application is loaded(require APP_PATH), directroy changed to rails root folder and  server.start is called. The code is as below:

module Rails
 class Server < ::Rack::Server
   def start
    trap(:INT) { exit }
    log_to_stdout if options[:log_stdout]

    puts 'Exiting' unless @options && options[:daemonize]

  def print_boot_information
   url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}"
   puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
   puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"
   puts "=> Run `rails server -h` for more startup options"

   puts "=> Ctrl-C to shutdown server" unless options[:daemonize]

So you can see that the start method doing basic stuff  like printing the boot message(the message you see after application.rb file loads), making temp directory etc and calling super, which means calling the method of same name from the parent class i,e from the Rack::Server class. Rack::Server is defined in another Gem rack .


Step 5: look into ::Rack::Server class
module Rack
  class Server

    attr_writer :options

    def initialize(options = nil)
      @options = options
      @app = options[:app] if options && options[:app]

    def app
      @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config

    def start &blk
      # ... wrapped_app, options, &blk

    def server
      @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default(options)

      def build_app_and_options_from_config
        if !::File.exist? options[:config]
          abort "configuration #{options[:config]} not found"

        app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
        self.options.merge! options

      def build_app_from_string

      def wrapped_app
        @wrapped_app ||= build_app app

So here you can see start calls wrapped_app function which call build_app function to which app function is passed which in turn call  build_app_and_options_from_config function, which have the code to load all the files in config folder.

Now you can understand, how all the files in config folder in rails are loaded automatically. The files are loaded from config folder in alphabetical order, the folder getting the first priority i,e config/environment folder/*.rb files  ->  config/initializer/*rb files -> other files in config folder

So we are done with the whole loading process below:

rails server -> Gemfile loaded -> boot.rb loaded -> application.rb loaded ->config/environments/development.rb   loaded -> config/initializers/* loaded    ->  config/environmet.rb loaded -> loaded -> server started



method overriding in ruby

method overriding refers to replacing a method of parent class in its subclass. The method definition in the subclass should have same signature as the method in the parent class. So, when a method is called on the subclass object, the overridden method in the subclass will be called.

lets create overriding_demo.rb file and add below line to it

class Person

  def welcome(name,msg,food)
	puts "Hi #{name}"
	puts "Hi #{msg}"
	puts "I will cook #{food} for you"


class Indian < Person

  def welcome(name,msg,food)
	puts "sorry..I do not know you"


puts "************welcome in parent class*************""arun", "how are you", "pizaa")

puts "\n\n************welcome in subclass*************""arun", "namaste..kaise hain app", "rice")

Now when you run the above file you will get the below output:

$ ruby overriding_demo.rb
************welcome in parent class*************
Hi arun
how are you
I will cook pizaaa for you

************welcome in subclass*************
sorry..I do not know you


So you can see that, welcome method is overrided in the subclass .Here an important aspect is use of super keyword , which allow the overriding method in subclass to execute the parent method and modify or add on its output.

So basically, super call the parent method implicitly. Obviously , you need to pass the arguments to the parent method. but super is not invoked as a normal method. super itself decide what argument to passed to the parent method when it is invoked in the subclass method, depending on the way , it is called.

Below are the convention used by super to pass argument to the parent method :

-> super called without any argument i,e simply as super then the argument passed to subclass method will be passed as argument to parent class .

-> super called with empty argument i,e as super() then no argument is passed to the parent method. It is useful if the parent method set some defaults and you want to stick to that . But, it will throw error, if the parent method expecting some arguments.

-> super called with arguments i,e as super(a,b,c) then only the argument a,b,c will be passed to the parent method.

To demo it, replace overriding_demo.rb file with below line of code:

class Person

  def welcome(name,msg,food)
	puts "Hi #{name}"
	puts "#{msg}"
	puts "I will cook #{food} for you"


class Indian < Person

  def welcome(name,msg,food)
    puts "I will show you bollywood movie"


puts "************welcome in subclass*************""arun", "namaste..kaise hain app", "rice")


run it, you will see below output

$ ruby overriding_demo.rb
************welcome in subclass*************
Hi arun
namaste..kaise hain app
I will cook rice for you
I will show you bollywood movie

So in the above code, the subclass call super to maintain the behavior of parent class and at the same time add some feature itself. Also note that the argument passed to the welcome method in the subclass get passed to the parent method implicitly.

now try to call the code again after replacing super with super() i,e calling with empty argument

$ ruby overriding_demo.rb
************welcome in subclass*************
welcome.rb:3:in `welcome’: wrong number of arguments (0 for 3) (ArgumentError)

So you get error which is expected as the welcome method need 3 arguments but you are not passing any

Again, modify the super in above code with super(“ajay”, “how are you”, “chinese”) and see the ouput again

$ ruby overriding_demo.rb
************welcome in subclass*************
Hi ajay
how are you
I will cook chinese for you
I will show you bollywood movie

So you can see that, this time welcome method of parent is invoked with argument passed to super.

That’s all about method overriding. just want to add that, you can override any thing in ruby, but avoid overriding inbuilt library methods as it may break other things in your class if that depend on the original method.

Leave a comment

method overloading in ruby

method overloading in programing refers to invoking different behavior of a method of class depending on its arguments. Making it simpler, you can say that a class can have more then one method with the same name, but with different argument i,e different signature of the method.

You can implement different signature of method in any of the below way:

1 : Arguments with different data types, eg: method(int a, int b) vs method(String a, String b)
2:  Variable number of arguments, eg: method(a) vs method(a, b)

Let’s try to do method overloading in ruby.

create a overloading_demo.rb file and add below lines to it

class Person

  def print_details(name)
    "Hey My Name is #{name}"

  def print_details(name,age)
    "Hey My Name is #{name} and #{age}"

person1 =
puts person1.print_details("arun")
puts person1.print_details("arun",25)

So, with overloading, you expect to get different message detail when you pass only name, and when pass both name and age.

Let see what we get by running the above code.

$ ruby overloading_demo.rb
overloading_demo.rb:7:in `print_details’: wrong number of arguments (1 for 2) (ArgumentError)

So, you can see that, overloading not happening here. ruby expecting print_details to have two argument, but since in the first call, you passed only one argument, it throws error. So we can say that:

Ruby do not support method overloading

In ruby there can be only one method with a given name. If there is multiple methods with the same name,the last one prevail i,e the last method will be invoked when called.

In above case, the last print_details method have two argument, so this will prevail and any call to print_details will expect two arguments. Since the first call to print_details passing only one argument, you are getting the above error.

But why ruby not support method overloading, when it is known feature in other language like C.

This is because  “Overloading” is a term that simply doesn’t even make sense in Ruby. It is basically a synonym for “static argument-based dispatch”, but Ruby doesn’t have static dispatch at all. So, the reason why Ruby doesn’t support static dispatch based on the arguments, is because it doesn’t support static dispatch, period. It doesn’t support static dispatch of any kind, whether argument-based or otherwise.

At the beginning, I have mentioned two way in which method overloading takes place : one when argument type differ and other when number of argument differ.

But ruby is dynamic typed language i,e type of the method argument is evaluated at the run time. You can see that, you have not specified the type of argument while defining print_details method, it is decided at run time so… print_details(int name,int age) and print_details(string  name, string age) is same in ruby. for variable no of argument implementation print_details(name, age=25) and print_details(name) definition is same, as they can be invoked with single argument.

Due to these issues ruby get rid of method overloading. Personally, I never felt its harming me in any way. In any case if you want to execute different behavior  for a method based on argument, you can write your own customize code. Lets modify our overloading_demo.rb to get what we want, without method overloading.

class Person

  def print_details(*args)
    case args.size
    when 1
      "Hey My Name is #{args[0]}"
    when 2
      "Hey My Name is #{args[0]} and #{args[1]}"


person1 =
puts person1.print_details("arun")
puts person1.print_details("arun",25)

No when you run the above code you can get the result you expect from overloading

$ ruby overloading_demo.rb
Hey My Name is arun
Hey My Name is arun and 25

Hope, you now have clear idea of method overloading in ruby

Leave a comment

polymorphism in ruby: duck typing with example

If you interested in technical jargon about polymorphism read here . Keeping it simple, polymorphism is object oriented programing approach where a interface behave differently depending on nature of the object.

what ? .. you still feel it is technical jargon.

O.K…lets make it more simple. being human we tend to meet people, greet them, treat them. Have you observed that people from different country, state or city do it in different way. A Englishman greet you with “Hi..How are you?” , a Indian from north say “namaste..kaise hain aap” …and so on.

So if you, program a welcome interface, its behavior should change depending on the person. This is known as Polymorphism.If you still didn’t get it, continue with the example, by end your concept will be clear.

class Welcome

  def meets
    puts "meets a person"

  def greet(person)

  def treat(person)


class Englishman

  def greet
    puts " are you?"

  def treat
    puts "Iam serving you English food"


class Indian

  def greet
    puts "Namste...kaise hain app"

  def treat
    puts "Iam serving you Indian food"


welcome =
puts "********Englishman***********"
person =

puts "********Indian***********"
person =

If you run the above file on console, you will again get the same output as in template implementation of inheritance.

$ ruby welcome.rb
********Englishman*********** are you?
Iam serving you English food
Namste…kaise hain app
Iam serving you Indian food


You can see that the welcome interface’s greet and treat method behaving differently for different person. This is known as polymorphism in Object oriented programing. The implementation is known as Duck Typing . The name come from initial proposed theory that a bird can speak and fly, but can do it in any ways, but still be treated as bird. They can be a duck or penguin or crow and so on

You can demo it on same line as welcome interface above. create a bird.rb file and add below code to it.

class Duck
  def speak
    puts "Quack I am #{@name}"
  def fly
    puts 'Up up and away...'
class Penguin
  def speak
    puts "Squak I am #{@name}"
  def fly
    puts 'Nope. I swim...'

class Bird
  def speak(bird)
  def fly(bird)

bird =

puts "***behave as duck****"
duck =

puts "***behave as penguin****"
penguin =

If you run the above file you will get below output:

$ ruby bird.rb
***behave as duck****
Quack I am
Up up and away…
***behave as penguine****
Squak I am
Nope. I swim…

Hope now you know what is Duck Typing and what is Polymorphism.