Tracking Events with Ahoy

Episode #303 by Teacher's Avatar David Kimura

Summary

Analytics can provide great information about your users and the content that you're producing. With using the Ahoy gem, we can gather powerful analytics without handing them over to third parties.
analytics rails 10:08

Resources

Download Source Code

Summary

# Terminal
bundle add ahoy_matey
bundle add faker
rails g ahoy:install
rails g scaffold article title content

# db/seeds.rb
25.times do
  Article.create(
    title: Faker::Lorem.sentence,
    content: Faker::Lorem.sentences.join(' ')
  )
end

# models/article.rb
class Article < ApplicationRecord
  visitable :ahoy_visit
end

# db/migrate/20210704023417_create_articles.rb
class CreateArticles < ActiveRecord::Migration[6.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.string :content
      t.bigint :ahoy_visit_id
      t.timestamps
    end
  end
end

# rails g migration add_ahoy_to_articles ahoy_visit_id:bigint

# articles_controller.rb
class ArticlesController < ApplicationController
  include Trackable

  ...

  def show
    track "Viewed Article", title: @article.title
  end
end

app/controllers/concerns/trackable.rb
module Trackable
  extend ActiveSupport::Concern

  def track(name, properties = {})
    ahoy.track name, properties
  rescue StandardError => error
    # notify error tracker
  end
end

# welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    @visits = Ahoy::Visit.includes(:events).all
  end
end

# views/welcome/index.html.erb
<table class='table'>
  <tbody>
    <% @visits.each do |visit| %>
      <tr>
        <td><strong><%= visit.ip %></strong></td>
        <td><strong><%= visit.user_agent %></strong></td>
      </tr>
      <% visit.events.each do |event| %>
        <tr>
          <td><%= event.name %></td>
          <td><%= event.properties %></td>
        </tr>
      <% end %>
    <% end %>
  </tbody>
</table>