Is there equivalent of python __getattr__ in ruby (for finding methods at least)?
class X(object):
def __getattr__(self, name):
return lambda x: print("Calling " + name + ": " + x)
x = X()
x.some_method("some args")
So it could be something like:
class X
# .. ??? ..
def default_action(method_name, x)
puts "Calling {method_name}: {x}"
end
end
x = X.new()
x.some_method("some args")
Yes. If an object does not respond to a message, Ruby will send a method_missing message with the message selector and the arguments to the receiver:
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)
# The message was :some_method.
# The arguments were "some args", :some_other_args, 42.
# And there was no block.
# NoMethodError: undefined method `some_method'
x.some_other_method do end
# The message was :some_other_method.
# The arguments were .
# And there was a block.
# NoMethodError: undefined method `some_other_method'
Note that if you define method_missing, you should also define respond_to_missing? accordingly. Otherwise you get strange behavior like this:
x.respond_to?(:foo) # => false
x.foo # Works. Huh?
In this particular case, we handle all messages, therefore we can simply define it as follows:
class X; def respond_to_missing?(*) true end end
x.respond_to?(:foo) # => true
class X
def method_missing(sym,*args)
puts "Method #{sym} called with #{args}"
end
end
a = X.new
a.blah("hello","world")
#=> Method blah called with ["hello", "world"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With