Upcoming and OnDemand Webinars View full list

Know Your Place, Cow!

Jonathan Wallace

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.

References:

Ruby Docs

Irb

http://old.nabble.com/Class_eval-vs.-reopening-class-td19125889.html

http://www.ruby-forum.com/topic/147243#651235

Not Happy with Your Current App, or Digital Product?

Submit your event

Let's Discuss Your Project

Let's Discuss Your Project