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!

Geplaatst in , ,  | 5 reacties

Reacties

  1. Radarek zei 4 dagen later:

    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.

  2. Michiel zei 4 dagen later:

    Bugs? What bugs? Our programs are gems of pure perfection.

  3. Chris zei 4 dagen later:

    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.

  4. Remco van 't Veer zei 4 dagen later:

    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!

  5. http://coderrr.wordpress.com zei 4 dagen later:

    a better way… http://coderrr.wordpress.com/2007/09/15/the-ternary-destroyer/

(Laat url/e-mail achter »)

   Voorvertoning