How to Count Page Impressions in Rails

The Impressionist Gem makes it surprisingly straightforward to track page counts in a Rails application. I recently added the feature to DailySmarty and below are the steps needed to implement it. Additionally, for performance reasons I integrated the counter with a counter cache, which means that the count is stored in the post record and therefore doesn't require a second database query to retrieve the current count.


Adding the Gem

You can integrate the official gem, however at the time of this post the migration isn't compatible with Rails 5.1+, I have a pull request in with the developer and in the meantime you can pull from my forked repo, followed by running bundle:

Run the Generator

With the gem installed, now you can run the generator and migrate the database.

Controller Configuration

Now update the controller(s) that you want to add the impression counting system to. First add the following method to the top of the class definition and list out the controller actions that you want to count:

And then update the controller action by wrapping the object with the impressionist method:

Configure Model

If you're using a counter cache, you need to add the new counter cache column to the model that you're working with. The following commands use the default column name that impressionist looks for:

Now you can update the model:

Render the View

With all of that in place you're ready to render the count, so the view code might look something like this: