The Beauty of
by Sean Cribbs
There are frequent times in development when you want to use
"keyword arguments" or in Rails-ish, an
options hash. I
had looked at some of the Hash extensions that are in the Rails
framework in the past, but I had rarely used anything more
reverse_merge is my friend.
Let's take a simple example: say you're making a helper that
displays your Person in a default way, where Person has the
:birthday. In this horribly contrived example, we'll
allow the user to specify the CSS style of each field, like so:
Part of the convention-over-configuration principle is providing defaults to reduce the amount of code and to create consistency. This is where the "options hash" comes in. Before when I wanted to do something like this, my code would look thusly:
Now let's turn it on its head with
Much better! (IMHO, YMMV)
reverse_merge works by
inserting only those keys that are not in the receiving Hash. Let's
clean it up a little more.
There you have it! Quick, simple and fool-proof "keyword arguments". One enhancement that could simplify it even further is to add our own little extension...