2 ms·
I love ruby, and find it great to use pry and irb to explore and figure stuff out. However, many times ruby libraries will use dynamic programming and method_m
by cortesoft 3y ago
I love ruby, and find it great to use pry and irb to explore and figure stuff out.
However, many times ruby libraries will use dynamic programming and method_missing to define methods on the fly… this makes it really hard to figure out what methods are actually available.
For that reason, I try to never use method missing to define core functionality in ruby, and hate when other gems do it.
- jaggederest 3y agoThe 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.