codedecoder

breaking into the unknown…


Leave a comment

simple file upload in rails

I have been doing file upload in rails using attachment_fu in initial days and then paperclip since its arrival. But have never used simple file upload i,e without using any gems. Recently I have to redesign the paperclip upload functionality of one of my application(will discuss in some other post), So thought of starting from beginning i,e how simple uploader works, what benefits paperclip or other available gem adds to it etc .

I am assuming you already have some rails 4 application running. We will add photo upload feature to it. This will be our flow.

->There will be a upload button on new photo page.
->User upload a pic using the simple uploaded.
-> On successful upload he will be redirected to show page, displaying the uploaded image.

generate the model and controller with below command on your project root from terminal

$ rails g model Photo pic:attachement
invoke active_record
create db/migrate/20150626122526_create_photos.rb
create app/models/photo.rb

If you see the generated migration file, it has below content

class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.attachment :pic
      t.timestamps null: false
    end
  end
end

Run migration to add the photos table

$rake db:migrate

Once the migration is complete and you chek the schema.rb file, you will see below detail of the photos table.

  create_table "photos", force: :cascade do |t|
    t.string   "pic_file_name"
    t.string   "pic_content_type"
    t.integer  "pic_file_size"
    t.datetime "pic_updated_at"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

So you can see that t.attachement in the migration file get converted into below 4 fields.

t.string “pic_file_name”
t.string “pic_content_type”
t.integer “pic_file_size”
t.datetime “pic_updated_at”

They represent internal property of any attachement. When user upload any file, you need to read these values from params and need to update these fields. Let generate the controller now

$ rails g controller photos new show create.

It will generate new, show and create action in photos controller and the corresponding views.
It will also generate get routes for all these actions.

  get 'photos/new'
  get 'photos/create'
  get 'photos/show'

remove them and replace with resourceful routes.

resources :photos

write the file upload code to the photos/new.html.erb

<%= form_for @photo, :url => photos_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :pic %>
  <%=form.submit 'upload'%>
<% end %>

This simply provide a file upload field with a upload button, which submit data to create action.

The whole controller code look as below:

class PhotosController < ApplicationController
  before_action :set_photo, only: [:show]

  def show
  end

  def new
    @photo = Photo.new
  end

  def create
    @photo = Photo.new
    @photo_object = params[:photo][:pic]
    @photo.pic_file_name = @photo_object.original_filename
    @photo.pic_content_type = @photo_object.content_type
    respond_to do |format|
      if @photo.save
        file_name_filesystem = @photo.id.to_s + @photo_object.original_filename
        photo_path_on_filesystem = Rails.root.join('public','uploads', file_name_filesystem)
        File.open(photo_path_on_filesystem,'wb') do |file| 
          file.write(@photo_object.read)
        end
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
      else
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  private
  def set_photo
    @photo = Photo.find(params[:id])
  end
end

The points to notice here is the create action. If you put debugger(I use byebug) inside the create action and try to see the params, it look as below

(byebug) pp params[:photo][:pic]
#<ActionDispatch::Http::UploadedFile:0xb3b9be60
@content_type=”image/jpeg”,
@headers=
“Content-Disposition: form-data; name=\”photo[pic]\”; filename=\”user1.jpeg\”\r\nContent-Type: image/jpeg\r\n”,
@original_filename=”user1.jpeg”,
@tempfile=#<File:/tmp/RackMultipart20150626-7518-liirs5.jpeg>>

(byebug) pp params[:photo][:pic].content_type
“image/jpeg”

(byebug) pp params[:photo][:pic].original_filename
“user1.jpeg”

(byebug) pp params[:photo][:pic].tempfile
#<File:/tmp/RackMultipart20150626-7518-liirs5.jpeg>

(byebug) pp params[:photo][:pic].tempfile.path
“/tmp/RackMultipart20150626-7518-liirs5.jpeg”

So you can see that params[:photo][:pic] is an object in itself from which we can get the name of the file, its content etc.

We have first saved file_name and content_type in db, and then write the files content in public/uploads directory of our project. So that when user visit show page next time we will show him the uploaded image.

NOTE: Instead of writing the content to filesystem, you can send it to any API which handle its storage or do whatever with the data you want to do.

Now in show.html.erb we have below code to render the uploaded photo.

 
<% pic_path = @photo.id.to_s + @photo.pic_file_name%> 
<%img src="/uploads/<%=pic_path%>" alt="" />

So from above implementation, now we can see what paperclip or other gem add to it:

-> You do not need to handle writing the uplaoded file to filesystem yourself. Gem will take care of it
-> Gem can handle storing the uploaded file on ThirdParty storage like amazone
-> They can provide further processing on image like creating tumbnail, applying affects etc.


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” host=getfinance.com request_id=0f4a7e2f-28a6-4542-a308-db3a9a72c0e6 fwd=”90.161.130.26″ 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'

routes

  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)
      apply_credit(args[1])
      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?
    end
  end
  
  def apply_credit(detail)
    begin
      uri = APP_CONSTANTS["credit_request_endpoint"]
      payload = "whatever xml or other data you want to send"
       rest_resource = RestClient::Resource.new(uri, {:user => "your username", :password => "xyz", :timeout => 60, :open_timeout =>60})
      credit_submit = rest_resource.post 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}
    end
  end
    
  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}
  end
  
end

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])}
end

def check_job_status
  job_status = BackgroundJobs.new.running_background_job(params[: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"
  end
  render :json => {:status => job_status[:status], :redirect_to => params[:current_path], :message => @message, :application_status => @application_saved}
end

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) {
    e.preventDefault();
    if ($('#accept_tc').is(':checked')) {
        var intervalId = '';
        
        $.ajax({
            url: "/loans/credit_request",
            data: $("#credit-request").serialize(),
            dataType: "json",
            type: "POST",
            success: function (job) {
              intervalId = setInterval(function () {
                  checkStatus(job,intervalId);
                }, 3000);
            }
          });
        
        $('#first_name').focus();
        $('#credit-request').block({
            message: null
          });
        return false;
      } else {
        alert('Please read and accept the terms, above, before submitting credit request.');
        $('#accept_tc').focus();
        return false;
      }
      
    })

function checkStatus(job, intervalId) {
    $.ajax({
        url: "/check_job_status",
        data: {
          job_id: job.job_id,
          current_path: job.current_url,
        },
        type: "get",
        dataType: "json",
        success: function (jobStatus) {
          console.log(jobStatus);
          if (jobStatus.status === 'complete' || jobStatus.status === "failed") {
              if (jobStatus.application_status === "Success") {
                  window.location = jobStatus.redirect_to;
                }
              else {
                  $('#ajax_message_success').hide();
                  $("#ajax_message_error").hide();
                  $("#ajax_message_error").text(jobStatus.message);
                  $('#ajax_message_error').show();
                  $("#application_tab").unblock();
                  $(window).scrollTop(0);
                }
                window.clearInterval(intervalId);
              }
            }
          });
      }

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'

Bundler.require(*Rails.groups)

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

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 @user.save, 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.


Leave a comment

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 http://0.0.0.0:3000
	=> Run `rails server -h` for more startup options
	=> Notice: server is listening on all interfaces (0.0.0.0).
	=> 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 config.ru
	Puma 2.8.2 starting...
	* Min threads: 0, max threads: 16
	* Environment: development
	* Listening on tcp://0.0.0.0:3000

 

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  ->  config.ru

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:

$PATH
-bash:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

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
begin
  load File.expand_path("../spring", __FILE__)
rescue LoadError
end
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 = Bundler.default_lockfile.read.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"
  end
end

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

#https://github.com/rails/rails/blob/master/railties/lib/rails/commands.rb
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'

Rails::CommandsTasks.new(ARGV).run_command!(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

Rails::CommandsTasks.new("server").run_command!(command)

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

    
 #https://github.com/rails/rails/blob/master/railties/lib/rails/commands/commands_tasks.rb
  def server
      set_application_directory!
      require_command!("server")

      Rails::Server.new.tap 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
        Dir.chdir(Rails.application.root)
        server.start
      end
    end

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:

#https://github.com/rails/rails/blob/master/railties/lib/rails/commands/server.rb
module Rails
 class Server < ::Rack::Server
   def start
    print_boot_information
    trap(:INT) { exit }
    create_tmp_directories
    log_to_stdout if options[:log_stdout]

    super
   ensure
    puts 'Exiting' unless @options && options[:daemonize]
  end

  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]
  end
 end
end

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

https://github.com/rack/rack/blob/master/lib/rack/server.rb
module Rack
  class Server

    attr_writer :options

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

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

    def start &blk
      # ...

      server.run wrapped_app, options, &blk
    end

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

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

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

      def build_app_from_string
        Rack::Builder.new_from_string(self.options[:builder])
      end

      def wrapped_app
        @wrapped_app ||= build_app app
      end
  end
end

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 -> config.ru loaded -> server started

 


2 Comments

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"
  end

end

class Indian < Person

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

end

puts "************welcome in parent class*************"
Person.new.welcome("arun", "how are you", "pizaa")

puts "\n\n************welcome in subclass*************"
Indian.new.welcome("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"
  end

end

class Indian < Person

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

end


puts "************welcome in subclass*************"
Indian.new.welcome("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}"
  end

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

person1 = Person.new
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]}"
    end
  end

end

person1 = Person.new
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"
  end

  def greet(person)
    person.greet
  end

  def treat(person)
    person.treat
  end

end

class Englishman

  def greet
    puts "Hi..how are you?"
  end

  def treat
    puts "Iam serving you English food"
  end

end


class Indian

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

  def treat
    puts "Iam serving you Indian food"
  end

end

welcome = Welcome.new
puts "********Englishman***********"
person = Englishman.new
welcome.greet(person)
welcome.treat(person)


puts "********Indian***********"
person = Indian.new
welcome.greet(person)
welcome.treat(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***********
Hi..how are you?
Iam serving you English food
********Indian***********
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}"
  end
 
  def fly
    puts 'Up up and away...'
  end
end
 
class Penguin
  def speak
    puts "Squak I am #{@name}"
  end
 
  def fly
    puts 'Nope. I swim...'
  end
end

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

bird = Bird.new

puts "***behave as duck****"
duck = Duck.new
bird.speak(duck)
bird.fly(duck)

puts "***behave as penguin****"
penguin = Penguin.new
bird.speak(penguin)
bird.fly(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.

 

Reference:

https://practicingruby.com/articles/duck-typing-in-practice-2

Follow

Get every new post delivered to your Inbox.

Join 29 other followers