Gems, Ruby

Ahoy

Hello, Folks. Welcome to my new article on Ahoy gem.

Recently, In one of the project, I was asked to implement user tracking (Tracking user visits, the pages visited etc). I was looking for an open source library for analytics. The very first ruby gem in my search result was Ahoy – A ruby gem to track visits and events.

Ahoy

  • Track visits and events in Ruby, JavaScript, and native apps
  • Works with any datastore
  • Easy to Integrate
  • Very handy

Installation
Add the following line to Gemfile and run ‘bundle’:

gem 'ahoy_matey'

Add the following line to javascript manifest (application.js) after jquery:

//= require jquery
// ...
//= require ahoy

DataStores

  • ActiveRecord based datastores – Postgres, MySQL, SQLite
  • MongoDB
  • Kafka, Fluentd, RabbitMQ, NATS, NSQ, or Amazon Kinesis Firehose
  • Logs
  • Custom

ActiveRecord Datastores – Postgres, MySQL, SQLite

Let use see how to setup Ahoy for ActiveRecord Datastores.

Run:

rails generate ahoy:stores:active_record

This will generate the following files:

  • db/migrate/20170504051029_create_visits.rb
  • app/models/visit.rb
  • config/initializers/ahoy.rb
  • db/migrate/20170504051030_create_ahoy_events.rb
  • app/models/ahoy/event.rb

Then, Run:

rake db:migrate

Ahoy Components

  • Visit

When a user visits the website, a record will be created in the visits table. The visits table includes information like IP, user agent, referrer, browser, os, country, city etc. The visits table include two columns – visitor_token and visit_token. Both visitor_token and visit_token are UUIDs and will uniquely identify a user session.

Use ‘current_visit’ method to access the visit record associated with the current user session

  • Event

All the user actions (page visits, button clicks, API calls etc) will be saved in the ahoy_events table. It has two columns – name and property. This two columns can be used to save the name of the event and additional properties like parameters in the request for that event.  Every record in the ahoy_events table will be linked to a record in the visits table.

Both the Visit and Event uses a polymorphic association to link to the User. You may use different tables for different users. In that case, the polymorphic association will help in tracking events and visits for the users.

Tracking

You can initiate the tracking through either ruby or javascript.

To track a visit using ruby:

  • ahoy.track_visit

To Track Events using:

  • Ruby
    ahoy.track "Event Name", title: "Test Event"

To track all rails action, add the below code to an after_action callback in the application controller as  below:

ahoy.track "Event Name", properties
Eg: ahoy.track "Viewed #{controller_name}##{action_name}", params
  • Javascript
    ahoy.track("Event Name", {title: "Test Event"});

    To track all events automatically

    ahoy.trackAll();

    The above will track all events – button clicks, page views etc.

To track events separately:

ahoy.trackView(); // Track page views
ahoy.trackClicks(); // Track clicks
ahoy.trackSubmits(); // Track form submits
ahoy.trackChanges(); // Track changes

Visit Duration

You can set an expiry on the visit record. By default, the visit duration is 4 hours. That is a new visit record will be created after 4 hours of inactivity. To override the default, visit duration add the following to ahoy.rb in initializers:

Ahoy.visit_duration = 30.minutes

Track Visits Immediately
Visitor and visit ids are generated on the first request (so you can use them immediately), but the track_visit method isn’t called until the JavaScript library posts to the server. This prevents browsers with cookies disabled from creating multiple visits and ensures visits are not created for API endpoints. Change this with:

Ahoy.track_visits_immediately = true

Disable Tracking For a Controller Action
To disable tracking for a controller action, add the following to the controller:

skip_before_action :track_ahoy_visit, only: :action

Override Track Visit and Event
To override the track visit and event action:

class Ahoy::Store < Ahoy::Stores::BaseStore
  def track_visit(options)
    # Add your code for overriding visit here
  end

  def track_event(name, properties, options)
    # Add your code for overriding event here
  end
end

Tips and Tricks

  • Reset ahoy visit after every user sign in. There may be a scenario in which a signed in user did sign out and again sign in as a different user. This may cause a mismatch with user_id in visits table and user_id for ahoy_events records for the new user. To reset ahoy visit for a controller action:
before_action :clear_ahoy_cookies, only: :action

 def clear_ahoy_cookies
  cookies[:ahoy_visit] = nil
  cookies[:ahoy_visitor] = nil
  cookies[:ahoy_event] = nil
  cookies[:ahoy_track] = nil
end
  • Track visit only if current_visit is not present. There are chances for multiple visit record creation.
    ahoy.track_visit unless current_visit

Try Ahoy and Have Fun!!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s