Thursday 20 November 2014

ActiveResource Custom calls response on get method

In this article i am going to explain one problem on active resource custom calls on get method and what the solution on that. Lets see whats the problem while you are making any active resource get calls. Lets see one example code snippet.

User.get(:active)  # GET /users/active.json
# => [{:id => 1, :name => 'Madhan'}, {:id => 2, :name => 'Ayyasamy'}]

User.get(:active, :awesome => true)  # GET /users/active.json?awesome=true
# => [{:id => 1, :name => 'Madhan'}]

Key Point: The objects returned from the called methods will be just ordinary hash only. It will not be automatically converted into ActiveResource::Base instances.

If you are expecting ActiveResource::Base instances, you have to use "find" class methods with ":from" option. This is the solution for the problem.

Then the new method will be like this

User.find(:all,:from=> :active)  # GET /users/active.json

# => <#User...> <#User...>.... (result as ActiveResource::Base instances).
Then you can use inside the iterations user.first.login_name something like this.

Thanks for reading this article. Hope it will be useful for you.


Saturday 8 November 2014

ActiveResource Post custom method calls in rails

In this article i am going to explain work around/fix for "wrong status line: "" issue while you are doing any activeresource stuff in rails.

What is the problem,why "wrong status line: "" while making resource calls on "post" verb?

Here is my code snippet where is the line making the problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class FactoringCashReceipt < ActiveResource::Base
  self.site = configatron.cync.factoring.url
  self.element_name = "cash_receipts"
  #self.prefix = "/borrowers/:borrower_id/"
  self.headers['X-BACK-KEY'] = BACKGROUND_SECRET_KEY

  def self.create_bulk_cash_receipts(batch,cash_receipts_objects)
    response = post("do_bulk_insert",{cash_receipts: cash_receipts_objects.to_json})
  end
  #def self.by_borrower(borrower_id)
  #  borrower_receivables = get("get_all_customers_by_borrower", {borrower_id: borrower_id})
  #end
  #
  #def self.by_invoice_no_lookup(lookup_no)
  #  customers = get("get_all_customers_by_borrower", {borrower_id: borrower_id})
  #end
  #
  #def self.by_borrower_with_lookup(borrower_id,lookup_no)
  #
  #end
  #
  #def self.by_borrower_with_customer_with_lookup(borrower_id,customer_id,lookup_no)
  #  receivable = find(:all, from: :get_particular_receivable, params: {borrower_id: borrower_id,customer_id: customer_id,receivable_no: lookup_no})
  #end
  #
  #def self.get_corresponding_receivables(params)
  #  receivables = find(:all, from: :get_corresponding_receivables, params: {borrower_id: params[:borrower_id],customer_id: params[:customer_id],receivable_no: params[:receivable_no]})
  #end

end

Problem on line no 8
response = post("do_bulk_insert",{cash_receipts: cash_receipts_objects.to_json})
The above line does not make a resource call to other engine. This line complaining that "URI is too long".
Now there is a question on your mind, what other options available to send large data on post call while activeresource. The answer is below

Proper Syntax  for post call is 

post(your_custom_method_name,options = {},body='')
so what mistake i did was, i passed all varibables inside the options which is passed as query parameter.

response = post("do_bulk_insert",{cash_receipts: cash_receipts_objects.to_json}) (Wrong Approach)
after modification the code should like this
Either
response = post("do_bulk_insert",{},{cash_receipts: cash_receipts_objects}.to_json) (Right Approach)
or
response = post("do_bulk_insert",nil,{cash_receipts: cash_receipts_objects}.to_json)
(Right Approach).

Hopefully now you can understand how post custom method calls on ActiveResource working and what common mistakes we do on that.

Thanks for reading this article.Hope it will be useful.


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 Hillite.me 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 "Hillite.me" for your reference.

Screenshot from hillite.me



















Here is the complete output after you complete above steps.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all.to_a
  end

  def show
  end

  def new
    @post = Post.new
  end

  def edit
  end

  def create
    @post = Post.new(post_params)

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

  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 }
      else
        format.html { render action: 'edit' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

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

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

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

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 github.com). The following simple steps you have to do get it done!.

1) Goto https://gist.github.com
2)  Login with your github.com 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 = Struct.new(:name,: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 = PersonAddress.new("Madhan","12,taulk office road, Mannargudi")
address2 = PersonAddress.new("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)

or
all_addresses.uniq!

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 = Set.new

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 = Set.new
PersonAddress = Struct.new(:name,:address_detail)
address1 = PersonAddress.new("Madhan","12,taulk office road, Mannargudi")
address 2 = PersonAddress.new("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 switch..case 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"
end

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

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",
}[params[:game_type]]

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

if @user.save
  respond_with user_path(@user)
else
  render_error @user

end

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}
}[@user.save].call

Conclusion:

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 = Time.now
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'
  end
end
puts "case: #{Time.now - time}"


time = Time.now
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"
    end
end
puts "if: #{Time.now - time}"


time = Time.now
1_000_000.times do
  msg = {
    :cricket => "playing cricket",
    :football => "playing football",
    :hockey => "playing hockey",
    :tabletennis => "playing tabletennis",
    :basketball => "playing basketball",
    :volleyball => "playing volleyball",
    }[game_type]
end
puts "hash: #{Time.now - 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
end

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
end

class CheckInvoice < ActiveRecord::Base
  belongs_to :check
end

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

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


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
end


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) }
    self.errors.clear
    final_errors.each { |err| self.errors.add(*err) }
  end
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!!!.