3 ms·
There's actually a fairly safe way to use method_missing. Just remember to call super if none of your conditions are met, that way you'll still get errors when
by jhickner 16y ago
There's actually a fairly safe way to use method_missing. Just remember to call super if none of your conditions are met, that way you'll still get errors when commands are misspelled. You really shouldn't ever use method_missing without that.
He probably also should be checking if @desk actually has a method with the provided name (with @desk.respond_to?(method_name)) before attempting to call it.
- epochwolf 16y agoWhen using method_missing in a proxy why bother checking? Just call the method and let wrapped object handle the errors. The stack trace will show you where to look for the error. The only reason I can see to check before calling is if you have different failure mode than the wrapped object. Otherwise you are duplicating logic.
- jhickner 16y agoIt's a small thing, I admit, but I like getting a slightly cleaner stack trace since the exception happens in the wrapper module (where the error is) instead of getting all the way to @desk.
- epochwolf 16y agoAfter I've spent the last 2~3 years reading funky rails stacktraces something like that doesn't bother me a bit. (I get more worried about older versions of jruby deciding to puke on internal ruby<->java mismatches at work) :)
- tomafro 16y agoHe should also define respond_to? on the DoNotDisturb class. Relying on method_missing to pass calls to respond_to? to the proxied class will not work, as it is defined in Object. Responding to a method when respond_to? returns false breaks the class contract.
- nusco 16y agoFrom the OP: I agree with you guys (or gals) on both calling super and redefining respond_to?(). Those are two of the "caveats" I mentioned at the end of the original post. I considered mentioning them explicitly, but the post is long enough already.