Created
January 19, 2022 10:20
-
-
Save guillaumecabanel/5a356c962a64828bedc1bbae6eea5da7 to your computer and use it in GitHub Desktop.
Consent Google Analytics in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/ app/views/shared/_google_analytics.html.slim | |
- if Rails.env.production? && session[:accept_google_analytics] | |
/ Global site tag (gtag.js) - Google Analytics | |
script[ | |
async | |
src=("https://www.googletagmanager.com/gtag/js?id=#{ENV['GOOGLE_ANALYTICS_TAG']}")] | |
javascript: | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', #{ENV['GOOGLE_ANALYTICS_TAG']}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/ app/views/layouts/application.html.slim | |
doctype html | |
html | |
head | |
= render 'shared/google_analytics' | |
/... | |
body | |
= render 'cookies/consent_banner' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/application_controller.rb | |
class ApplicationController < ActionController::Base | |
# [...] | |
before_action :set_cookies_acceptation | |
private | |
def set_cookies_acceptation | |
if !session[:accept_google_analytics].present? | |
if params[:accept_google_analytics] == 'yes' | |
session[:accept_google_analytics] = 'yes' | |
end | |
if params[:accept_google_analytics] == 'no' | |
session[:accept_google_analytics] = 'no' | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/locales/fr.yml | |
fr: | |
cookies: | |
deny: Refuser | |
ok: Accepter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment