Cleanly add logging to your method calls with metaprogramming
If you’re running your Ruby scripts on a cron job, it’s important to log the output in case something goes wrong. Recording the output is as simple as appending “> somefile.txt” to your cron job. But can you avoid cluttering your code with lots of “puts” statements? Using a bit of metaprogramming, you can write a module that adds logging to whatever methods you specify. In this blog post, I’ll show you how.
Comments
I stopped taking this article seriously the moment I saw “define_method” in the code.
Really? What would you use instead? Eval doesn’t seem like a good option.
Look into how Rails implements alias_method_chain. http://metautonomo.us/2011/02/03/when-to-use-alias_method_chain/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+metautonomous+%28metautonomo.us%29
Paul - what I’m doing is basically what that article shows, except that the names of methods to be aliased and redefined has to be determined dynamically. But the basic challenge of redefining the behavior of a method that’s defined on the class itself is the same.
Post a comment