CommonThread

Tip: Rails Options Helpers

Posted by anthony crumley, Wed Jan 09 14:54:00 UTC 2008

Ok, so these are not really helpers but they are helpful. Rails often uses a hash as the last method parameter to pass options. When the method has a variable number of parameters there is a need to pull the options hash out of the arguments array. To do this they added an extract_options! method to the Array. This method removes and returns the last argument in the array if it is a Hash.

def some_method(*args)
  options = args.extract_options!
  ..
end

Another common options problem is setting default values. Rails added reverse_merge to the Hash object to help out here.

def some_method(*args)
  options = args.extract_options!
  options.reverse_merge!({:limit => 10})
  ..
end

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.




Categories