Our Daily Method #18: NilClass#method_missing
Geplaatst door Remco van 't Veer vr, 29 feb 2008 07:40:00 GMT
Warning: only apply the following under parental guidance!
We know the whiny nil, as applied in Rails, but what about an obedient nil:
class NilClass
def method_missing(*args)
nil
end
end
No more monkeying like:
person && person.name && person.name.upcase
Not DRY at all! Let’s use the obedient nil instead:
person.name.upcase
This concludes our last daily method. Ode to Michiel for providing a vast amount of nice tricks!
Please, do not show code that is as bad and useless. Good luck with this code to search bugs… Sorry guys bad I have to write this.
Bugs? What bugs? Our programs are gems of pure perfection.
NoMethodErrors (even from nil) can be helpful, and can even help you track down typos. ‘underscored’.gsub!(’_’,’ ‘).upcase will, with NilClass#method_missing like this, return nil, and it might not be obvious why. And if you misspell an instance variable name somewhere it might be hard to track down if NilClass is silently swallowing method calls.
It’s interesting to see the comments the nil post yields compared to the other daily method posts. I guess I should have made the warning big, fat and blinking.
For everybody who didn’t get it: it’s stupid and dangerous, it will blowup in your face, set your pants on fire, steal your girlfriend and eat your lunch!
a better way… http://coderrr.wordpress.com/2007/09/15/the-ternary-destroyer/