Skip to content

Instantly share code, notes, and snippets.

@guillaumecabanel
Created January 19, 2022 10:20
Show Gist options
  • Save guillaumecabanel/5a356c962a64828bedc1bbae6eea5da7 to your computer and use it in GitHub Desktop.
Save guillaumecabanel/5a356c962a64828bedc1bbae6eea5da7 to your computer and use it in GitHub Desktop.
Consent Google Analytics in Rails
/ 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']});
/ app/views/layouts/application.html.slim
doctype html
html
head
= render 'shared/google_analytics'
/...
body
= render 'cookies/consent_banner'
# 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
# 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