9
8

More than 3 years have passed since last update.

RailsでGoogleAnalyticsを設定する

Posted at

Railsで作成したアプリにGoogleAnalyticsを設定することがたくさんあると思う。
google-analytics-railsという便利なgemがあるそうだが、PRを見てみると2017年10月で終わっている…
多分メンテナンスされていないし、gemを使うほどでもないので自分で設定することにしたが、RailsからJavascriptへの変数の渡し方に手間取ったので残しておく。

Analyticsタグの設置

GoogleAnalyticsタグはheadに書いていく。今回はログインしている場合は変数current_userをJavascriptに渡してあげて、ログインしていない場合は変数を渡さないという仕様にする。
このcurrent_userをRailsからJavascriptに渡す時にかなり工夫した。

コード

コードを書いていく。テンプレートエンジンはslimを使っている。

app/views/layouts/application.slim.html

doctype html
html
  head
    meta content=("text/html; charset=UTF-8") http-equiv="Content-Type"
    = csrf_meta_tags
    = stylesheet_link_tag 'application', media: 'all'
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
    - if Rails.env.production?
      = render './google_analytics'

Analyticsは本番環境だけで動かしたいのでif Rails.env.production?の中に入れる。
Analyticsスクリプトは他のファイルでも使う可能性があり使いまわしたいので、部分テンプレートで共通化しておく。
先に答えを出すと、下記のようなコードになる。

app/views/layouts/_google_analytics.slim.html

script async="" src="https://www.googletagmanager.com/gtag/js?id=#{トラッキングID}"
javascript:
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'トラッキングID');
  if (#{raw current_user.to_json}) {
    gtag('set', {'user_id': #{raw current_user.to_json}.id});
  }

RailsからJavascriptに変数を渡す場合、その変数のデータ型がintegerの場合はそのまま渡して問題ないが、それ以外の場合はcurrent_user.to_jsonというようにto_jsonをつけてあげないといけない。
また、エスケープ処理をさせないために、ActionView::Helpers::OutputSafetyHelperで用意されているrawメソッドを使用する。
こうすることで、Railsのcurrent_usergonなどを使わずに渡すことが出来た。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8