Creating a simple hit counter in Rails

2.7k views Asked by At

I've been trying to implement the gem Impressionist, but as the doc is confusing and the gem carries a bit of overhead for my simple use case I wonder how I could go about implementing this myself?

  • I want to track impressions (requests) of a certain action in a controller.

  • The impressions don't have to be registered by unique visitors.

  • I need the counter to be unique to each record in the model (i.e. Shop 1: 34 hits, Shop 2: 77 hits etc).

  • The counter should not include requests from bots on this list: http://www.user-agents.org/allagents.xml

What would be the minimal code required to accomplish the above?

Update

To clarify, if possible I don't want to use the gem Impressionist. I only used that as a prelude to describe what problem I'm trying to solve.

1

There are 1 answers

0
fotanus On BEST ANSWER

You need to add an attribute to your model.

If you are using the Impressionsit gem, you should use the built-in migration generator to add the correct scheme to your database.

Otherwise, if you are not planing to use this gem, you will need to create a migration like the following:

MyMigration < ActiveRecord::Migration
  def change
    add_column :pluralized_model_eg_users, :integer, default: 0
  end
end

Then, on the actions you want to count, use the code :

unless request.env["HTTP_USER_AGENT"].match(/\(.*https?:\/\/.*\)/)
  @model.update_attribute :impressions, @model + 1
end

It does not uses the list you gave even to avoid overhead. However, most robots have an url in his user agent to identify then, so using this should be safe.

Using the list from this site would need you to add a caching to that list, which might add uneeded complexity in your code if it aims to be a simple feature.