0

We need to find a good place to store page metrics as a rails page loads. It'll include stats, initially how many times certain slow methods are used. We're using a class variable on ApplicationController at the moment but that seems like code smell. Is there a better way to do this?

class ApplicationController < ActionController::Base
  cattr_accessor :page_stats

  def increment_slow_stuff()
    @@page_stats ||= {}
    @@page_stats[:slow_stuff] ||= 0
    @@page_stats[:slow_stuff]  += 1
  end

  def slow_method()
    increment_slow_stuff()
    ...
  end
end

2 Answers 2

1

Why not use an instance variable? If you later need to store it for longer, you could always save a record at the end of the pageview. Plus, a PageStats model would let you do more advanced analysis of your metrics.

Sign up to request clarification or add additional context in comments.

1 Comment

This turned out to be the way to go. What I was forgetting was that the rails controller is easily accessible from the view. No need for globals.
1

The issue with this method of doing it is that the stats will only be around as long as the class is. I would recommend writing to a database or maybe even Redis.

You could also subscribe to these events so that the code isn't inside your controllers using the technique shown in this Railscast

2 Comments

Was just writing the same answer about the using ActiveSupport::Notifications. To me, that's definitely the way to go. It nicely decouples your stats collection.
Thanks. I neglected to mention that I only need the metrics around for single page. We'll output these stats in a footer that only site admins will see. ActiveSupport::Notifications looks promising. Upon further searching, rails-footnotes looks like it might be an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.