Four Key Reasons to Learn Markdown
Back-End Leveling UpWriting documentation is fun—really, really fun. I know some engineers may disagree with me, but as a technical writer, creating quality documentation that will...
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
Writing documentation is fun—really, really fun. I know some engineers may disagree with me, but as a technical writer, creating quality documentation that will...
Humanity has come a long way in its technological journey. We have reached the cusp of an age in which the concepts we have...
Go 1.18 has finally landed, and with it comes its own flavor of generics. In a previous post, we went over the accepted proposal and dove...