I love abusing method_missing in Ruby, it is great fun.
module IsDoesIsntDoesnt
def method_missing(method, *args)
m = method.to_s
if (m =~ /^is_(\w*?\?)$/) || (m =~ /^does_(\w*?\?)$/)
real_method = $1.to_sym
return send(real_method, *args) if respond_to?(real_method)
elsif (m =~ /^isnt_(\w*?\?)$/) || (m =~ /^doesnt_(\w*?\?)$/)
real_method = $1.to_sym
return !send(real_method, *args) if respond_to?(real_method)
elsif (m =~ /^(\w*?)s\?$/)
real_method = "#{$1}?".to_sym
return send(real_method, *args) if respond_to?(real_method)
end
super.method_missing(method, *args)
end
end
Object.class_eval() do
include IsDoesIsntDoesnt
end
Which lends itself to these types of natural statements:
?> "team".includes?("i")
=> false
>> "team".isnt_empty? => true
and:
>> [].is_empty? => true
>> [ :stuff ].does_include?(:stuff) => true
While I’m sure Ruby mavens will think of much nicer ways to implement this type of functionality, I had fun doing it.
An exercise for the reader would be to dynamically add the appropriate method, so the next call doesn’t rely on method_missing.







o | 07-Mar-08 at 12:21 pm | Permalink
Oh, god.
Ruby’s the next pink, innit?
Tal Rotbart | 07-Mar-08 at 12:23 pm | Permalink
LOL, you’re late to the game!
Ruby was the next pink a year ago, now Scala is the next Ruby. Well not really, but close.