extract_options bang 25 Jul 2007
I’ve seen and used a lot of slightly different mechanisms for grabbing an options hash from a passed in set of arguments. Today the Rails core team has added a helper to the Array class as part of Rails’ core extensions. It’s a simple addition, but one that I like.

With Options

arr = [ 1, 2, 3, { :validate => true } ]
options = arr.extract_options! 

# arr = [ 1, 2, 3 ]
# options => {:validate=>true}

Without Options

arr = [ 1, 2, 3 ]
options = arr.extract_options! 

# arr = [ 1, 2, 3 ]
# options => {}

DHH has removed the method extractoptions_from_args_ which used to exist in ActiveRecord::Base in favor of extract_options!. Using extract_options will be preferred over doing things like:

args.last.is_a?(Hash) ? args.pop : {}

Actual Code Example 1 - ActionView::Helpers::FormBuilder

def fields_for(object_name, *args, &block)
  raise ArgumentError, "Missing block" unless block_given?
  options = args.extract_options!
  object  = args.first

  builder = options[:builder] || ActionView::Base.default_form_builder
  yield builder.new(object_name, object, self, options, block)
end

Again it’s on Edge as of today, so if you don’t live on the Edge you won’t see it for awhile unless you implement itself for your project. Doing so may keep things tidy as you continue your projects rails development.


blog comments powered by Disqus