Saturday, 2 August 2014

How to Beautify your code snippet and implement in Blogger

If you are writing technical blogs, sometimes you have to give some sample programs. Few ways are there to beautify your code snippet one is attaching Gist code into your blogger(How to include your gist code snippet into your blogger). Other turn around is, i am going to explain in this blog post.

I am working on Ruby on Rails, so most of my tech articles based on either Ruby or Rails side only. So if the users are coming to my site, if they are looking any code snippets if language based and highlighted means, its very easy to understand. So that purpose we have make beautify our code snippets. Here is very less steps to follow to make your code as beautify with language specific.

1) Goto website.
2) In "source code" text box, just enter your code which you want to display in your posts.
3) Select "Language" dropdown, which language is for your code snippet.
4) Select "Style" dropdown, which style you want. There is plenty of style options are there. I personally prefer "monokai".
5) Select "Line Numbers" check box if your code snippet with line numbers (Optional only). Otherwise dont select.
6) In CSS text box, just enter the color of border and spacing stuff( Probably you no need to modify anything, default style itself is fine).
7) Yes you are almost done. Just you need to click the button called "Highlight!".
8) You can see Preview immediately. If any further changes you need just modify and click "Highlight!" button again.
9) Copy  auto generated code from "HTML" text box. Below is the snapshot i have attached from the website of "" for your reference.

Screenshot from

Here is the complete output after you complete above steps.

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all.to_a

  def show

  def new
    @post =

  def edit

  def create
    @post =

    respond_to do |format|
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @post }
        format.html { render action: 'new' }
        format.json { render json: @post.errors, status: :unprocessable_entity }

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { head :no_content }
        format.html { render action: 'edit' }
        format.json { render json: @post.errors, status: :unprocessable_entity }

  def destroy
    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }

    def set_post
      @post = Post.find(params[:id])

    def post_params
      params.require(:post).permit(:title, :description)

Thursday, 31 July 2014

How to Include Gist code snippet into Blogger

If you are writing some technical blogs, sometimes you need to give some sample code snippets. If you are planning to use your gist content(which is provided by The following simple steps you have to do get it done!.

1) Goto
2)  Login with your username and password.
3) First text box is gist description. You just give meaningful name.
4) In the next text box, you have give the file name with the extension. For my case i have used extention as ".rb". So file name text box i will give like "first_ruby_program.rb". Then "Language" dropdown automatically select as "Ruby". Because of your file name having the extention of ruby.

5) Next text box, you can enter your code which you want to come your blog.
6) Click "Create Public Gist" button, for generate gist file for your content.
7) Copy the script from "Embed URL". If you are planning to use your gist content in blogger.

Thats it from Gist side. Following steps have to do in blogger side.

1) Create/edit existing post. Paste the code where you copied from gist "Embed URL" text box. Here is the screenshot for how to get the "Embed URL" from gist.
embed url from gist

2) Check "Interpret typed HTML Line breaks" option is checked on. For this settings you have to see "Post settings" in right side bar and then click "Options". You can see the option. Below is the screenshot i attached for easy navigation purpose.

blogger settings

3) Save your changes, before publish better you can see the preview. Here is the screen shot how finally gist code snippet will appear in your blog.

Gist sample snapshot

Now you can see neatly formatted and highlighted code snippets from gist. Hope you can feel this is useful tips. Thanks for reading!!!

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).