I've written a little wrapper over method_missing
like this:
module Util
def method_missing_for(regex, &blk1)
define_method(:method_missing) do |name, *args, &blk2|
match = name.to_s.scan(regex).flatten[0]
if match
blk1.call(match, *args, &blk2)
else
super(name, *args, &blk2)
end
end
end
end
Then using it:
class Foo
extend Util
method_missing_for(/^say_(.+)$/){ |word| puts word }
end
Foo.new.say_hello
# => "hello"
The problem is that I cannot call this multiple times for a class. The method_missing
I add with define_method
just gets overridden. What alternative do I have? Conceptually I know I can refactor method_missing_for
to take multiple regex => block mappings and then call it once instead of multiple times. At its core it would be a big case statement which tests all the regex. But I would rather be able to take advantage of super
.
class Foo
extend Util
method_missing_for(/^say_(.+)$/) { |word| puts word }
method_missing_for(/foobar/) {}
end
Foo.new.say_hello # => NoMethodError