Railsで簡単アクセス解析をする場合に使うgem

最近はサービスを立ち上げてそれを発展させる上でアクセス解析というものは必須になっていると思います。多くの場合はGoogleさんを使っていると思いますが、gemもあるので、それを使ってみました。

Ahoyというツールです。

使い方は簡単です。

1.Gemfileに以下を追加

gem 'ahoy_matey'

2.関連ファイルをジェネレート


$bundle install --path vendor/bundle/
$bundle exec rails g ahoy:install
$bundle exec rake db:migrate

作成されるテーブルはvisitsテーブルです。

class InstallAhoy < ActiveRecord::Migration
  def change
    create_table :visits do |t|
      # cookies *required*
      t.string :visit_token
      t.string :visitor_token

      # the rest are recommended but optional
      # simply remove the columns you don't want

      # standard
      t.string :ip
      t.text :user_agent
      t.text :referrer
      t.text :landing_page

      # user
      t.integer :user_id
      t.string :user_type

      # traffic source
      t.string :referring_domain
      t.string :search_keyword

      # technology
      t.string :browser
      t.string :os
      t.string :device_type

      # location
      t.string :country
      t.string :region
      t.string :city

      # utm parameters
      t.string :utm_source
      t.string :utm_medium
      t.string :utm_term
      t.string :utm_content
      t.string :utm_campaign

      t.timestamp :created_at
    end

    add_index :visits, [:visit_token], unique: true
    add_index :visits, [:user_id, :user_type]
  end

ユーザの情報だけでなく、ipや国情報、OS、デバイス情報など後々解析するのに必要な情報がこのテーブルに入ります。

後は、application.jsにahoy.jsを追加して準備完了です。

実際にアクセス状況を見たいときはvisitテーブルに対してActiveRecord経由で見ることができます。
これも選択肢として考えても良いなという感想です。