Friday, April 11, 2008

Quick Tip - extract_options!

ActiveSupport added a helpful method named 'extract_options!' that

"Extracts options from a set of arguments. Removes and returns the last element in the array if it‘s a hash, otherwise returns a blank hash."

So when we have a method that can accept multiple attributes the last of which could be a hash of options, instead of doing...

def some_method(*attributes)
configuration = {
:some_default => 'value'
}
configuration.update(attributes.pop) if attributes.last.is_a?(Hash)
.......
end

We have the more elegant...


def some_method(*attributes)
configuration = {
:some_default => 'value'
}
configuration.update(attributes.extract_options!)
.......
end

No comments: