breaking into the unknown…

Leave a comment

heroku timeout code H13

Recently while going live with one of our financial domain project on Heroku we get with this dreaded error.

at=error code=H13 desc=”Connection closed without response”

The error occurring whenever a user try to submit his loan application. Basically a user never able to submit his application due to the above error as the process getting killed due to response taking too long to comeback.

some of the culprit line in logs look like as below:

2015-06-08T19:10:34.297539+00:00 heroku[router]: at=error code=H13 desc=”Connection closed without response” method=POST path=”/loans/credit_request” request_id=0f4a7e2f-28a6-4542-a308-db3a9a72c0e6 fwd=”″ dyno=web.2 connect=0ms service=26007ms status=503 bytes=0
2015-06-08T19:10:34Z app[postgres.32439]: [MAUVE] could not receive data from client: Connection reset by peer
2015-06-08T19:10:34.277236+00:00 app[web.2]: E, [2015-06-08T19:10:34.277078 #3] ERROR — : worker=0 PID:9 timeout (26s > 25s), killing

So basically Heroku is not to blamed. It is right in killing a process if it see no response coming in 25 second.

We know that oue API is the culprit. This is how our whole application work

-> User come to our application build in rails
-> Fill the details related to loan he want to apply and submit it.user see progress bar rotating
-> On submit we capture the data and make a API call to another application written in java.
-> The API do a lot of processing on the data, create citadel certificate, register the user on OpenAm,trigger few emails etc and then send back response.
-> when response is success we reload the page with success message or render the error

It is the second last step in which Heroku seeing a problem. Heroku keep waiting for the response, and when it see that it is exceeding 25 second, it kill the existing process, so the user page never get refreshed and hanged for ever with the progress bar rotating.

So we know the problem…but what will be the solution.

Idle solution is to improve on our API code and make it to return a response in say 15 second(our taking between 25 to 30 seconds). but it is long term plan. we are already live and it is not that we have not worked on reducing the response time(well it is crime if you make user to wait 30 second for response) but since a lot of processing undergo before sending the response, we can’t do much.

So we decided to live with the current response time and fool Heroku to believe that request response cycle is working.

Here is the Plan:
-> push the API call to background job
-> submit the form as ajax
-> In the action which handle submit, trigger the background job and render the job_id , the path to which need to be redirected and other parameter you want to reuse
-> On success of ajax request, trigger another ajax call to a separate method which keep checking the status of the job after a fix interval say 3 seconds.
-> when the second ajax call see that status is complete, it will reload the page

So now, although user see some increase in time due to overhead introduced in checking status after every 3 seconds, Heroku see the request response cycle working as in every 3 second it see a request coming asking for the job status and a response going on with the current status : pending , queued, running etc .

So here is the code:

Add sidekiq to Gemfile and run bundle install

gem 'sidekiq'
gem 'sidekiq-status'


  resources :loans
  post 'credit_request' => 'loans#check_credit_request', :as => :credit_request
  get 'check_job_status' => 'loans#check_job_status', :as => :loan_status

write the background code in lib folder say – lib/application.rb

require 'rest_client'
require 'base64'

module LoanPath
  class Application
    include Sidekiq::Worker
    include Sidekiq::Status::Worker
    sidekiq_options :retry => false
    def perform(*args)
      lp_status_code = background_task_output[:lpcode].present? ? background_task_output[:lpcode] : ""
      lp_status_message = background_task_output[:lp_message].present? ? background_task_output[:lp_message] : ""
      lp_data = background_task_output[:lp_data].present? ? background_task_output[:lp_data] : ""
      store :lp_status_code => lp_status_code
      store :lp_status_message => lp_status_message
      store :lp_data => lp_data
      at 100,100, background_task_output[:lp_message] 
                   if background_task_output[:lp_message].present?
  def apply_credit(detail)
      uri = APP_CONSTANTS["credit_request_endpoint"]
      payload = "whatever xml or other data you want to send"
       rest_resource =, {:user => "your username", :password => "xyz", :timeout => 60, :open_timeout =>60})
      credit_submit = payload, :content_type => "application/xml"
      {:lpcode => "LpValid", :lp_message => "Credit Request Submitted Successfully", :lp_data => credit_submit}
    rescue Exception => e
      error_message = "System encountered error, please try later"
      {:lpcode => "LpError", :lp_message => error_message, :lp_data => nil}
  def running_background_job(job_id)
    status = Sidekiq::Status::status(job_id)
    status_message = Sidekiq::Status::message(job_id)
    lp_status_code = Sidekiq::Status::get(job_id, :lp_status_code)
    lp_status_message = Sidekiq::Status::get(job_id, :lp_status_message)
    lp_data = Sidekiq::Status::get(job_id, :lp_data)
    {:status => status.to_s, :status_message => status_message, 
     :lp_status_code => lp_status_code, :lp_status_message => 
     lp_status_message,:lp_data => lp_data}

The loan view to fill the details is as below:

<%= form_tag credit_request_path, :method => :post, :id => "credit-request" do %>
   your form fields
   <%= submit_tag 'Submit Credit Request', :id => 'apply-credit'%>
<% end %>

controller code which handle the loan submit is as below:

def credit_request
  job_id = LoanPath::Application.perform_async("apply_credit", params)
  render :json => {:job_id => job_id , :current_url => loan_url(params[:id])}

def check_job_status
  job_status =[:job_id])
  @application_saved = "Error"
  if (job_status[:lp_status_code].to_s == "LpValid")
    @application_saved = "Success"
    @message = "Credit Application Submitted Successfully."
  elsif (job_status[:lp_status_code].to_s == "LpError")
    @message = job_status[:lp_status_message].present? ? 
               job_status[:lp_status_message] : 
               "System encountered error, please try later"
  render :json => {:status => job_status[:status], :redirect_to => params[:current_path], :message => @message, :application_status => @application_saved}

Now the most important, the  js code which submit the form through ajax and keep checking status is as below

$('#apply-credit').click(function (e) {
    if ($('#accept_tc').is(':checked')) {
        var intervalId = '';
            url: "/loans/credit_request",
            data: $("#credit-request").serialize(),
            dataType: "json",
            type: "POST",
            success: function (job) {
              intervalId = setInterval(function () {
                }, 3000);
            message: null
        return false;
      } else {
        alert('Please read and accept the terms, above, before submitting credit request.');
        return false;

function checkStatus(job, intervalId) {
        url: "/check_job_status",
        data: {
          job_id: job.job_id,
          current_path: job.current_url,
        type: "get",
        dataType: "json",
        success: function (jobStatus) {
          if (jobStatus.status === 'complete' || jobStatus.status === "failed") {
              if (jobStatus.application_status === "Success") {
                  window.location = jobStatus.redirect_to;
              else {

That’s all now Heroku will not complain about Timeout error

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.



Leave a comment

ruby plugins for netbeans

Netbeans has removed ruby support since version 7.0 . So now it do not come inbuilt with Netbeans 7.0 or 7.3 or 8.0 or any other higher version, but still available as plugin from ruby community.

You can add it with below simple steps :

=> Start your Netbeans IDE

=> Go to  Tools -> Plugins -> Settings

=> Click Add on the setting page. It will open a new window for you and provide fields to enter plugin name and URL

=> Name it ruby (you can give any name you want) . within the URL provide below.

=> click O.K to complete the plugin addition

=> Now click on Available Plugins tab and search for ruby or whatever name you have given to the plugin.

=> The ruby plugin will be listed in the search, click it to select and you will see install button appear at the bottom

=> just click install and follow the instruction like accept agreement, click next etc

If you do not get next button at any stage, it may be due to some missing dependency .

Earlier I was using some other URL for the plugin

and getting below message in the installation window with the next button inactive

plugin is requested in version 1.0

If you face similar problem.. read this blog

=> You are done, now you can use netbeans for your Ruby development as usual…. Be Happy 🙂