CommonThread - Our Blog

Recent Articles

Tip: Rails Options Helpers

Tip: Rails Options Helpers

Written By: Anthony Crumley

January 9th, 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

2 Responses to “Tip: Rails Options Helpers”

  1. Matt Farley Says:
    osw0emu0dr8bp3yu
  2. Rafael Says:
    Hi, Thanks, just the info I needed. I didn't want to look for the details or look the Rails code at 4 AM :) Cheers, Rafael.

Leave a Reply