RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

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.

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

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in