1. Skip to navigation
  2. Skip to content

The ELC Community Blog

A knowledge exchange on Ruby on Rails and Agile Development


Hit Tracker Plugin

by josh on September 05, 2007

ELC Plugins

HitTracker is a very simple plugin to give you quick and easy functionality to track access to your records using ActiveRecord. Whether you need to track page views, record updates or search results, HitTracker can help you do it.

This is not an ideal solution for heavily trafficked sites, but for smaller ones it provides quick and no-hassle hit tracking.

Usage

1. Install the plugin:

./script/plugin install http://svn.elctech.com/svn/public/plugins/hit_tracker

or with SVN external reference:

./script/plugin install -x http://svn.elctech.com/svn/public/plugins/hit_tracker

Add a migration to create the hits table:

class CreateHits < ActiveRecord::Migration
    def self.up
        create_table :hits do |t|
            t.column :hittable_type, :string
            t.column :hittable_id, :integer
            t.column :kind, :string
        end
    end

    def self.down
        drop_table :hits
    end
end

3. Configure your models to use the plugin:

class Article < ActiveRecord::Base
    track_hits
end

4. Add the hit requests to your controller:

def show
     @article = Article.find(params[:id])

     # Here, 'PageView' can be replaced with any string
     # to help you distinguish your hits
     hit(@article, 'PageView') 
end

It works for collections too!

def results
    # replace the following with your your favorite search query
    @search_results = Article.find_by_solr(query)

    # the following will create one hit for each item
    # in your collection
    hit(@search_results, 'SearchResult')        
end

5. Access your hits anywhere with:

# a collection of hits on the current object
@article.hits

# the total number of hits on the object
@article.hit_count

That's all there is to it!

Comments

Add a comment


home | services | Ruby on Rails Development | code | blog | company