back

How delegate works in Rails, Part I

Delegate is a 17 line method that helps you follow the Law of Demeter in Rails code.

It’s short and useful. It also demonstrates a lot of Ruby idioms.

Let’s look at it line by line. Do read the delegate documentation if you haven’t already.

First, the method accepts arguments with the splat operator, which calls .to_a as well as siphons the arguments.

It then grabs the options from the arguments array using array.pop, which removes the last item from an array and returns it.

Next it makes sure that the arguments that it just popped off the array are a hash. If not it raises an argument error.

The next part is a bit more complex. Since delegate can take a class variable (@@variable) or a CONSTANT, the case checks to make sure that the :prefix option is not being passed in if we’re delegating to a constant or a class var.

It does this using the regular expression matching operator which “returns the position in a string where a match was found, or nil if the pattern did not match.”

In this example, =~ will return 0 if the thing being delegated to is not a method. (Remember, 0 is true in Ruby) This is because if we were delegating to, for example, a class variable, we might pass:

  delegate :sum, :to => :@@class_array, :prefix => :fail

So then,

  :@@class_array.to_s =~ /^[^a-z_]/ #=> 0

So, in the above case, we would get an argument error.

This is getting lengthy, so let’s drop into part two.

December 08, 2008