Fellow Stranger
Fellow Stranger

Reputation: 34113

Creating a simple hit counter in Rails

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?

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.

Upvotes: 3

Views: 2781

Answers (1)

fotanus
fotanus

Reputation: 20126

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.

Upvotes: 2

Related Questions