Making today worse so tomorrow seems better.

Using New Relic Add_method_tracer With Class Methods

on

At Vocel we use the New Relic plugin to monitor the performance of our production Rails apps.

In addition to the built-in ActiveRecord and Controller metrics, you can define your own custom metrics. The documentation clearly shows how to add a metric to an instance method, but how do you add one to a class method?

I’m using custom metrics to differentiate between time spent in our app and time spent waiting for external components. So we can imagine that we have a class like:

The problem with this is that the New Relic add_method_tracer call expects an instance method. So when we add the custom metric inside the class definition it is unable to find the method that it is supposed to be tracing. It’s looking for get_recommended_for_subscriber not Product.get_recommended_for_subscriber.

The key to the solution is that in Ruby, Class methods are just instance methods on the singleton object that defines the class. So instead of dealing with the class methods on the class, we want to operate on the instance methods of the singleton. Luckily we can get access to the singleton definition by using the “class << self” syntax.

You’ll see the “class << self” idiom used a lot inside the Rails code itself. I generally favor the “def self.method_name” syntax, because it makes it clear that this is a class method. But in this case the real power of the class singleton came in very handy.