We have introduced Google Analytics to collect data on the web service that we have developed this time and are about to release, so we will introduce how to do it. There is a gem called google-analytics-rails and there is also a way to use it, but when I look at github, the update stopped around October 2017 (Readme was updated last month), so I'm worried So this time I introduced it without gem.
[Prerequisites] -Registered in Google Analytics. (Registration method is here)
Just prepare a partial template for Google Analytics and load it with the head tag.
haml:layauts/_google_analytics.html.haml
%script{async: "", src: "https://www.googletagmanager.com/gtag/js?id=Tracking ID"}
:javascript
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'Tracking ID');
if (#{raw current_user.to_json}) {
gtag('set', {'user_id': #{raw current_user.to_json}.id});
}
haml:application.html.haml
!!!
%html
%head
%meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
- if Rails.env.production?
= render 'layouts/google_analytics'
The point here is the last if statement, which converts current_user to json and passes the data if you are logged in.
It also uses the `ActionView :: Helpers :: OutputSafetyHelper``` raw method to avoid escaping. You can do the same with html_safe, but it seems that the raw method is recommended as it will raise an exception if it is nil. (Looking at the [Rails Guide](https://guides.rubyonrails.org/active_support_core_extensions.html#output-safety), it says
To insert something verbatim use the raw helper rather tha calling html_safe:
`` There is.)
https://qiita.com/t1gert1ger/items/b9a197e2d85050b9d7d6
I output what I learned every day! I hope it helps you. If you have any suggestions, I would appreciate it if you could comment.
Recommended Posts