Tuesday, August 6, 2013

Rails action caching with querystring parameters

We can cache a particular action with its query string parameters in rails as follows :

caches_action :action_name, :cache_path => Proc.new { |c| c.params }

Use of "!~" operator in Ruby

"!~" can be used to have conditional statements to check if string doesn't match particular regular expression. So that whenever we want to check if particular string is not matching a regular expression we can avoid having negative conditional statements using "unless" like

unless "str" =~ /reg_exp/
 # do something
end

We can write this conditional statement as assertive condition as follows:

if "str" !~ /reg_exp/
 # do something
end

Interpolating Instance, Class level or Global variable in Ruby

When the expression to be interpolated into the string literal is simply a reference to a global, instance or class variable, then the curly braces may be omitted.

So the following should all work: 

@first_name = "Anil"
puts "#@first_name Galve"  #=> "Anil Galve"

@@first_name = "Anil"
puts "#@@first_name Galve" #=> "Anil Galve"

$first_name = "Anil"
puts "#$first_name Galve"  #=> "Anil Galve"

Monday, August 5, 2013

before_save vs before_validate in Ruby On Rails

If we want to manipulate data before saving into database we tend to use before_save for example if we want to trim users first name before saving to database we would normally use before_save callback and will do something like below:

before_save :trim_first_name

def trim_first_name
  first_name = first_name.strip
end

But there is gotcha into it, it will skip validation for updated first_name because before_save callback gets executed after validations. So lets say, if there uniqueness validation for first_name and if there is already user with first_name "anil" present in database and if user specify "anil " then that user will be inserted since later one has extra space and it skips that validation and before saving into database it strips the first_name and defeats the purpose of our validation.

Hence, whenever we want to manipulate data before saving into database its good idea to have before_validation callback instead of before_save callback.

Same can be achieved like below:

before_validation :trim_first_name

def trim_first_name
  first_name = first_name.strip
end