Know Your Place, Cow!

Jonathan Wallace

2 min read

Oct 1, 2010

Know Your Place, Cow!

Have you ever had a problem with rude cows in Ruby? If you have unruly class methods that need proper handling, read on.

In a recent project, there was an unruly class method available in a gem. This method could do horrible destructive things if called and though we had no plans to ever call it, we wanted to make sure that it would never ever ever be called in the future, even on accident. And if it was called, we wanted to make sure that it was neutured, incapacitated, harmless, if you will.

How can one override the default behavior of a method in ruby? That’s an easy one. alias_method_chain to the rescue. This is common knowledge and armed in our arrogance we fired up our favorite editor (vim FTW!!) and coded up an initializer. The results were as follows.

Oh, no! What went wrong? Where’s that famous dynamic meta-programming available in ruby? Have we been misled? Does this mean rails can scale? Double rainbow? What does it all mean?

Never fear, intrepid reader! Further sleuthing led us to the correct answer.

alias_method_chain is a wrapper around alias_method and alias_method expects method names. We can’t pass self.goodbye_with_manners to alias_method_chain as it fails to properly handle a) the context of a class method and b) a period in the middle of the “method name”.

The secret is to fire off alias_method_chain in the context of class method definitions. One way to do that, which we used here, is to grab a reference to the singleton class.

Dangerous method is now neutured. Rude cows now have manners (sort of). The world is safe once again.


Ruby Docs


Mark Dalrymple

Reviewer Big Nerd Ranch

MarkD is a long-time Unix and Mac developer, having worked at AOL, Google, and several start-ups over the years.  He’s the author of Advanced Mac OS X Programming: The Big Nerd Ranch Guide, over 100 blog posts for Big Nerd Ranch, and an occasional speaker at conferences. Believing in the power of community, he’s a co-founder of CocoaHeads, an international Mac and iPhone meetup, and runs the Pittsburgh PA chapter. In his spare time, he plays orchestral and swing band music.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News