Yes. If the object does not respond to the message, Ruby will send the message method_missingusing the message and argument selector to the recipient:
class X
def method_missing(selector, *args, &blk)
puts "The message was #{selector.inspect}."
puts "The arguments were #{args.map(&:inspect).join(', ')}."
puts "And there was #{blk ? 'a' : 'no'} block."
super
end
end
x = X.new
x.some_method('some args', :some_other_args, 42)
x.some_other_method do end
Note that if you define method_missing, you must also define respond_to_missing?accordingly. Otherwise, you will get strange behavior as follows:
x.respond_to?(:foo)
x.foo
In this particular case, we process all messages, so we can simply define it as follows:
class X; def respond_to_missing?(*) true end end
x.respond_to?(:foo)
source
share