Rodrigo Flores's Corner Code, Cats, Books, Coffee

Ruby Patterns: Method with options

This is a series about Ruby Patterns, which will explain some common uses of Ruby syntax. The first post is about methods with options.

Let’s start with an example where it can be useful. Suppose, you’re given an object and you should write a method that prints the object’s attributes in HTML. Also, you’ll also have to follow this other requirements:

  • You may specify the attributes that you want to show (by default you should show all of them);
  • You may specify the attributes that you don’t want to show (by default, you should show all of them, i.e. this list is empty);
  • You may specify the format: possible formats are :ordered_list, :unordered_list, :table (by default, present it as a :table);
  • You may specify the strftime format of the objects of Time type (default is :month/:day/:year :hour::minute :timezone in strftime format);
  • You may specify the strftime format of the objects of Date type (default is :month/:day/:year in strftime format);

So, given this requirements. Let’s write a function:

def object_to_html(object, only=nil, except=[], format=:table, time_format="%m/%d/%Y %H:%M %t", date_format="%m/%d/%Y")
  only ||= object.attributes - except

  if only - except != only
    fail "You can't put in except an attribute that you've put on only"

  # Code that does what we proposed

Some examples of the usage of this function (and what someone will say after reading your code):

object_to_html(user) # Seems OK
object_to_html(user, nil, :encrypted_password) # What is this nil ?
object_to_html(user, [:email, :phone, :created_at], [], :ordered_list, "%d/%m/%Y %H:%M", "%d/%m/%Y") # WTF is this empty array ?
object_to_html(product, nil, [], :table, "%d/%m/%Y %H:%M", "%d/%m/%Y") # Gosh. My eyes are bleeding. Call an ambulance.

What a creepy code! If you want to change the last attribute, you will have to know all the default values of the other ones to be able to change it. You will also have to know (or constantly look at its implementation or documentation) the exactly order of the attributes. Also, if you decide to remove one attribute, you will have to find all the calls to this method and change it on all of them. Definitely, this is what I call ugly code: difficult to use and hard to maintain.

So, this pattern comes in handy: method with options!

def object_to_html(object, options={})
  default_options = {
    :format => :table,
    :only => nil,
    :except => [],
    :time_format => "%m/%d/%Y %H:%M %t",
    :date_format => "%m/%d/%Y"

  options = options.reverse_merge(default_options)

  options[:only] ||= object.attributes - options[except]

  if options[:only] - options[:except] != options[:only]
    fail "You can't put in except an attribute that you've put on only"

  # Code that does what we proposed (now it uses the options hash instead of local variables)

The same usage examples come along:

object_to_html(user, :except => [:encrypted_password])
object_to_html(user, :only => [:email, :phone, :created_at], :format => :ordered_list, :time_format => "%d/%m/%Y %H:%M")
object_to_html(product, :time_format => "%d/%m/%Y %H:%M", :date_format => "%d/%m/%Y")

Now to the explanation of how this works: the Hash#reverse_merge! method does the key role here. It merges the two hashs (the one containing the default values with the one that was given as a parameter) and in case of the same key in both, it keeps the one that belongs to the Hash that received the method call (in our case, the one given as a parameter to the method). The method is called reverse_merge because the Hash#merge method solves the conflict in the opposite way: in case of the same key in both, it keeps the one that belongs to the hash given as argument on merge. We can easily use merge instead of reverse_merge if we write the line 10 this way:

options = default_options.merge(options)

And then the code would work the almost the same way: the only difference is that instead of accessing local variables we may access the arguments in the options hash, but this can be easily converted. Also, note that we’re adding a bang (!) so, it will modify the hash and do the merge on itself instead of not modifying and returning other instance of hash.

Also, if you want to enforce that one option is always given, you can do this:

rescue KeyError # Hash#fetch raises KeyError when a key is not found
  raise ArgumentError, "The :format option should be passed"

Doing this, you will treat a missing argument the same way Ruby does with the function calling. However, I’m not a big fan of this approach: I think that if an argument is mandatory, it should be passed as a regular argument and not on as a function.

This pattern is heavily used on famous Ruby libraries like Rails, Bundler or Devise and plays a big part on pretty DSLs like Rails routes or Gemfiles. So, IMO, you should use it wherever you find a need to include more than 2 or 3 arguments on a function. Also, it is possible to use this on Javascript: if you take a look at jQuery’s ajax function it works the same way: you can pass the url as the first argument and the other parameters (like callbacks, fallbacks, urls, etc) as an object.

A big disadvantage in doing this is that it is very difficult to know what is the default options, and even looking at your code, you may only understand what is the default behaviour passing through all the code (which is far from good). So, I suggest that you document the default parameters and what does they mean like Rails do in this example with the has_many method.

UPDATE: As Rafael França suggested, I’m not overriding the argument anymore. As hashes are passed as a reference, when you execute merge! you actually change the parameter outside the function as an undesirable side effect.

UPDATE II: Adam Meehan reminded me on the comments that Hash#reverse_merge is part of ActiveSupport and not part of Ruby standard library. To be able to use it, you will have to require activesupport/core_ext/hash.

comments powered by Disqus