Unobstrusive metaprogramming, by Sean O’Halpin

I watched Sean O’Halpin 30-minute Ruby Manor presentation (Nov 2008) called “Unobstrusive metaprogramming”. He gave a few tricks about monkeypatching.

Here are my highlights.

Problems with monkey patching “the Rails way”

  • namespace pollution
  • documentation pollution
  • cognitive pollution

Case in point:

>> [Kernel, Object, Class, Module].inject({}){|hash, klass| hash[klass] = klass.methods.size; hash}
=> {Object=>98, Kernel=>159, Module=>99, Class=>99}
>> require active_support
=> true
>> [Kernel, Object, Class, Module].inject({}){|hash, klass| hash[klass] = klass.methods.size; hash}
=> {Object=>187, Kernel=>225, Module=>188, Class=>188}

Recommendations

  • indirect access (using functions)
  • namespaces
  • hide your mess

So for instance, instead of monkey patching the Array object, we can do something like that:

a = [[1,2,3,[4],5]]
Doodle::Utils.flatten_with_1_level(a) # => [1,2,3,[4],5]

The plea

Don’t monkeypatch: Object, Kernel, Module, Class, Hash, Array, etc.

Everytime you monkeypatch Object, a kitten dies.

Advertisements

One comment

  1. lol “Everytime you monkeypatch Object, a kitten dies.” . Nice article!

Got a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: