3 ms·
The responsible thing when you use `method_missing` is to define `respond_to` to indicate whether an object responds to a particular method. This alleviates the
by jaggederest 3y ago
The responsible thing when you use `method_missing` is to define `respond_to` to indicate whether an object responds to a particular method. This alleviates the "is a method available" issue because you can just ask the object "Do you respond to :method_I_want_to_call?", and it will correctly inform you it does or does not. This kind of discoverability is one of the things I miss when I'm working in Javascript/TS as I have been recently - sure you can check the .method_name property to see if it's a function and then execute it but it doesn't feel as nice.
E.g.
def method_missing(name, \*args)
if name =~ /^has_/
has(name, *args)
end
super
end
def respond_to(name)
if name =~ /^has_/
return true
end
super
end
- cortesoft 3y agoSure, but my favorite thing to do in irb is <object I want to inspect>.methods.sort - Object.methods This won’t work even with respond_to being defined
- danielheath 3y agoI also love this technique . I prefer to subtract {}.methods though - shorter to type and removes more cruft.
- ajmurmann 3y agoHah, I am even twice as lazy as you and do '- 1.methods'. Works for 99.9% of cases.