Friday, 11 April 2014

Usage of Set in Ruby

In this article, I am going to explain when should we use a Set in ruby language. Lets go with some real examples. If you are planning to create a person address with few columns like name and address_detail. Simply you can use like this

PersonAddress =,:address_detail)

May be in some cases you have to create a list of  person addresses and want to list of those. That time you have use array like this.

address1 ="Madhan","12,taulk office road, Mannargudi")
address2 ="Ayyasamy","53/1,3rd cross,3rd main,4th cross, Laxmi Layout, Near subash cable office, Bangalore-560068")

If you want to make a list of person address you created then you have to push it into array like this

all_addresses = []
all_addresses << address1
all_addresses << address2 

Now you are thinking all_addresses should have uniqueness facility. This time what you will do for uniqueness of address. Either you have to use include? command or uniq! method. So code should be like this

all_addresses << address1 unless all_addresses.include?(address1)


If you missed above way then duplicate will add into array.

all_addresses << address1
# => [address1]

all_addresses << address2
# => [address1,address2] all_addresses << address1
# => [address1,address1,address2] 

Now the time to think about "Set" class in ruby language. If you  want a result as a collection with unique then go for "Set". Lets look into following example.

require 'set'
all_addresses =

There is no modification on PersonAddress struct. Change is only on array variable only, instead of array we are using "Set" to store the address information.

So full code become as follows.
require 'set'
all_addresses =
PersonAddress =,:address_detail)
address1 ="Madhan","12,taulk office road, Mannargudi")
address 2 ="Ayyasamy","53/1,3rd cross,3rd main,4th cross, Laxmi Layout, Near subash cable office, Bangalore-560068")

all_addresses << address1
=> #}>
all_addresses << address2
=> #, #}>

Now if you are adding again duplicate entry like 
all_addresses << address1
# =>  #, #}>
2.0.0-p195 :041 >

See above result there is no chance when you add duplicate entry. Thats the real usage of "Set" in Ruby Language.

Conclusion of this post is, array also fine way to achieve the above scenario, if you want to accept duplicate. Better you need to define your data in proper way using proper classes available in ruby, that way you have a more control on your data. The data also will work as much you expect. Finally you should consider about performance also the classes provide flexibility. If you are not bothering about your way of implementation then you will end up with ugly code then later you have to revisit your code for better tuning in form of performance. So better you decide proper classes which you want to boost performance and control about your data as you expect.
Hopefully you can enjoy this article, will catch you later.

Wednesday, 26 March 2014

Ruby Hash Selector Pattern

If you are building some web applications, in some scenario you should route or redirect depends upon your logical conditions. There is so many ways to put your logical conditions on the code. For example most of the people will use either if..else or statement(in Ruby). Anyway result is same only but execution time will vary depends upon which way you are implementing the stuff. In this article, we are going to learn how to use Hash selector pattern for logical options.

Let's take first one using if.. else selector pattern.

if params[:game_type] == :cricket
  "playing cricket"
elsif params[:game_type] == :football
  "playing football"
elsif params[:game_type] == :hockey
  "playing hockey"
elsif params[:game_type] == :tabletennis
  "playing tabletennis"
elsif params[:game_type] == :basketball
  "playing basketball"
elsif params[:game_type] == :volleyball
  "playing volleyball"

But above code looks bit ugly. we can achieve same result using switch/case also. Lets see how to convert the same code into switch/case selector pattern.

cash params[:game_type]
  when :cricket then "playing cricket"
  when :football then "playing football"
  when :hockey then "playing hockey"
  when :tabletennis then "playing tabletennis"
  when :basketball then "playing basketball"
  when :volleyball then "playing volleyball"

Compare if..else, switch/case will be more readable and easy to understand for new readers. Main thing is switch/case pattern will take very less time to execute the code than if..else pattern. so if you want to put more elsif conditions better to use switch statement to get more boost on performance area.

Lets jump into Hash selector pattern, how to achieve the same things
:cricket => "playing cricket",
:football => "playing football",
:hockey => "playing hockey",
:tabletennis => "playing tabletennis",
:basketball => "playing basketball",
:volleyball => "playing volleyball",

see Hash pattern selector is more readable than swith/case pattern!!!.

Now we are going to know how to use hash selector pattern in Procs/lamdas

The above example, just printing the message or just assigning value using the hash pattern is not that much special. What about calling methods using that? can we use hash pattern to call methods?. Yes we can definitely do. Lets look at the following example.

May be you have this kind of logic in your controller

  respond_with user_path(@user)
  render_error @user


The above code we can convert into hash pattern in the following way,

 true =>  -> {self.respond_with user_path(@user)},
 false => -> {self.render_error @user}


Important thing is if you are using hash selector pattern might be your performance will be slow compare switch/case statement. so better to use switch/case statement if you are planning to put more elsif condition scenario. This article to show you how to use hash selector pattern but if you are asking me regarding performance, i wont suggest you to use hash selector patter. Here i have attached benchmark result for your reference in all there pattern( like if..elsif,switch/case and hash selector pattern). Just look the result than you will decide which way you have to go ahead.

All three pattern benchmark results,look at the code snippets

 game_type = :cricket

time =
1_000_000.times do
msg = case game_type
  when :cricket then 'playing cricket'
  when :football then 'playing football'
  when :hockey then 'playing hockey'
  when :tabletennis then 'playing tabletennis'
  when :basketball then 'playing basketball'
  when :volleyball then 'playing volleyball'
puts "case: #{ - time}"

time =
1_000_000.times do
  msg = if game_type == :cricket
      "playing cricket"
    elsif game_type == :football
      "playing football"
    elsif game_type == :hockey
      "playing hockey"
    elsif game_type == :tabletennis
      "playing tabletennis"
    elsif game_type == :basketball
      "playing basketball"
    elsif game_type == :volleyball
      "playing volleyball"
puts "if: #{ - time}"

time =
1_000_000.times do
  msg = {
    :cricket => "playing cricket",
    :football => "playing football",
    :hockey => "playing hockey",
    :tabletennis => "playing tabletennis",
    :basketball => "playing basketball",
    :volleyball => "playing volleyball",
puts "hash: #{ - time}"

case: 0.465138302
if: 0.582026524
hash: 3.581798935

Hope you can understand how to use Hash selector pattern and how it will impact performance area and all. Will catch you on another article!!!

Tuesday, 11 March 2014

How to get rid of "X is invalid" error message in validates_associated method in rails

While i am using validates_associated in my project, it gave "x(some model) name is invalid" error. I will give proper example. Batch is one model, Check is another model and Check invoices is another model. So my active record models looks like as follows.

class Batch < ActiveRecord::Base
  has_many :checks, dependent: :destroy
  has_many :check_invoices, through: :checks
  accepts_nested_attributes_for :checks, allow_destroy: true
  validates_associated :checks

class Check < ActiveRecord::Base
  # Associations
  belongs_to :batch
  belongs_to :borrower
  has_many :check_invoices, dependent: :destroy

  accepts_nested_attributes_for :check_invoices, allow_destroy: true
  validates_associated :check_invoices

class CheckInvoice < ActiveRecord::Base
  belongs_to :check

so my case, while i am trying to save Batch(parent model) user can enter check details as well as check invoices details also.

Problem is, any check model is invalid its giving error messages associated with checks but it gave some unwanted message like "Checks is invalid".  Because validates_associated default message option has "is invalid" string. So this default message will append in your child associated model even though if you define individual level error messages.

Solution 1: Above i explained what is the problem, now i am going to explain how to fix it in global manner/individual model level.

lets create one customer validator file called "my_custom_validates_associated.rb" in config/initializers folder in your rails application.

That file should have following content which you can use anywhere in the models.

module ActiveRecord
  module Validations
    class MyCustomValidatesAssociated< ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        #(value.is_a?(Array) ? value : [value]).each do |v|
        #  unless v.nil?
        #    record.errors.full_messages.each do |msg|
        #      #record.errors.add(:base, "msg")
        #    end
        #  end

    module ClassMethods
      def own_validates_associated(*attr_names)
        validates_with MyCustomValidatesAssociated, _merge_attributes(attr_names)

After adding this file into your config/initializer folder then you have to restart your server then only you will get effect.

Now your model needs little bit change due to our new custom validator added into our application.

Now my own validation associated should work with only checks model then i have to change in Batch model. Now new code looks like as follows.

class Batch < ActiveRecord::Base
  has_many :checks, dependent: :destroy
  has_many :check_invoices, through: :checks
  belongs_to :cash_receipt_source_code ,:foreign_key => "batch_source_code_id"
  accepts_nested_attributes_for :checks, allow_destroy: true
  own_validates_associated :checks

Now you wont get "X is invalid/Checks is invalid" default error message in your error messages list.

Solution 2:

The above one is created for generic level. If you want to use only one model then you can filter error messages and remove "X is invalid" message then assign back to other error messages into model.errors.add method. Those as follows for your reference.

  def after_validation
    # you can filter unwanted messages that is not userfriendly.
    final_errors = self.errors.reject{ |err| %w{ user User  }.include?(err.first) }
    final_errors.each { |err| self.errors.add(*err) }
in your model, you can to call the above method on after_validation call back.

Here i attached final output before and after the code change for your understanding.

 Before custom validator how the message is coming with "Checks is invalid"

After we added custom validator called own_validates_associated method,see the desired output error messages.

Hopefully you can enjoy this article. Thanks for reading!!!.

Thursday, 6 March 2014

How to retain old text box value using JQuery

In my scenario, i have one table that contains multiple rows, each row will have one checkbox. Once you checked the checkbox , other column(example invoice balance there is some numeric amount column) value has to populate in other text box value which is applied amount column. Once you uncheck the checkbox you should retain what was the old value in applied amount column, may be its came from db.
The following image will show the exact scenario what i am trying to say above.

How to retain old text box value using jquery

After lot of googling, i found a solution in single line of code using pure javascript. But Many people they are achieving same stuff using temp variable. Those are really not needed in my observation. Lets jump into exact solution how to fix it....

<script language="JavaScript">
function check_invoice_row_status(check_box)
var current_amount_old_value = $("#""").parent().parent().find("input[type='text'][id*='current_amount']").prop("defaultValue");
var adjustment_amount_old_value = $("#""").parent().parent().find("input[type='text'][id*='adjustment_amount']").prop("defaultValue");


Main code which i mention one line code is  $("input[type='text'][id*='current_amount']").prop("defaultValue") ; Will return the old value(db saved value).

Thanks for showing interest to read this article.

Monday, 6 May 2013

Staging and Unstaging area in GIT

In this article, i am going to explain what is mean by staging area and unstaging area in git.

Staging area means, whatever files you have changed in your working tree and added into index using git add (command) . Thats called as "staged" area(but not yet committed). Simply we can tell "changes that are staged but not committed".

If you want to see the list of files you have added into the index, use the following command
git diff -- staged

Unstaging means, changes that not yet added into the index. simply we can tell as "changes that have not been added into the index". To view the unstaged files do the following commands

git diff (Will give you the overall files whatever you changed/modified as well what changes you have done in each and every files in your working tree).

Sunday, 7 April 2013

How to create a patch in git

In this article, i am going to explain how to create a patch in Git Version control. Before look into that how to do that, we need to ask a question our self why we have to go with "patch" instead of merge option is available in git.

What a need of patch?

If you have master branch with bug free(just example), in later if you want to work with any enhancement/future kind of stuff you can create a new branch called "future". So once all enhancements are done you can merge "future" branch into "master" branch. For example in your future branch shared with multiple developers so obviously your "future" branch will have good amount of commits. So while you merge with "master" later, you can do it in two ways one is "merge" and another one is "patch"(create a patch and apply that patch into master branch). If you go with "merge" option, reverting back to previous version is little bit headache( because git will creates so many merge commits). suppose if you choose patch style, it will be single commit for your entire "future" branch changes. Lets see how to do it in git as command.

just assume you are in future branch and you have done all necessary changes on that branch, just we want to create a patch

git checkout future (if you want create a patch from "future" branch)
git diff master >> my_patch_name.patch

Now go to your master branch and then apply created patch from future branch.

git checkout master
git apply my_patch_name.patch
git add .
git commit -m"future branch merged with master"
git push origin master

It will create a single commit in master after you applied patch, just delete that patch file which the file has extention .patch. Good thing is if you want to revert back to your previous commit too easy.

Hopefully you can enjoy this article!!!.

How to checkout other branch exact files in git

Here i am going to explain you, how to checkout other branch particular file in your working tree or current branch. Just assume your current working directory is "future"(git branch name is future).
You have one more branch called "master". Suppose if you want to checkout particular file from master branch into your future branch. Then do the following command it will work out well.

Lets move to your current branch, here "future" using following command

git checkout future

Now you shifted into "future" branch. Then do the following command, which we need exactly for our need(checkout particular file from master branch).

git checkout master -- file_1_name.txt,file_2_name.txt
(Just for examples file_1_name.txt and file_2_name.txt. According to your need you can change into your desired filenames list).

The above command will override your current branch(future branch) files you mentioned above command. So your local changes will be ignored.

Hopefully now you come to know how to checkout other branch files in your current branch!!.