Thursday, June 21, 2007

"duck typing made easy".gsub(/y$/, 'ier')

I was reading through the ever amazing Beast Forum code and came across this bit in distance_of_time_in_words method of application helper.

from_time = from_time.to_time if from_time.respond_to?(:to_time)

Duck typing is great, and you should use it when possible, but look at how ugly it makes things. You have to type to_time twice, once as a method and once as a symbol. The object has to be typed twice as well, maybe if I had some fancy Textmate snippet or something to help me. Or some slightly clever Ruby code.

def method_missing(method, *args)
  return super unless method.to_s =~ /_if_respond_to$/
  method_name = method.to_s.gsub(/_if_respond_to$/, '')
  return self unless self.respond_to? method_name
  return self.send(method_name)
end

Now we can easily do:

from_time.to_time_if_respond_to
# => Thu Jun 20 17:25:13 -0400 2007

123.to_s_if_respond_to
# => "123"


# What if it doesn't respond_to? your method?
123.to_roman_numerals_if_respond_to
# => 123

No comments: