Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Google Analytics 4 #164

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/rack/tracker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
require "rack/tracker/handler_delegator"
require "rack/tracker/controller"
require "rack/tracker/google_analytics/google_analytics"
require "rack/tracker/google_analytics4/google_analytics4"
require "rack/tracker/google_global/google_global"
require "rack/tracker/google_tag_manager/google_tag_manager"
require "rack/tracker/google_adwords_conversion/google_adwords_conversion"
Expand Down
41 changes: 41 additions & 0 deletions lib/rack/tracker/google_analytics4/google_analytics4.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Rack::Tracker::GoogleAnalytics4 < Rack::Tracker::Handler

self.allowed_tracker_options = [:cookie_domain, :user_id]

def initialize(env, options = {})
super(env, options)
end

class Send < OpenStruct
def initialize(attrs = {})
attrs.reverse_merge!(type: 'event')
super
end

def write
['send', event].to_json.gsub(/\[|\]/, '')
end

def event
{ hitType: self.type }.merge(attributes.stringify_values).compact
end

def attributes
Hash[to_h.slice(:category, :action, :label, :value).map { |k,v| [self.type.to_s + k.to_s.capitalize, v] }]
end
end

def tracker
options[:tracker].respond_to?(:call) ? options[:tracker].call(env) : options[:tracker]
end

private

def tracker_option_key(key)
key.to_s.camelize(:lower).to_sym
end

def tracker_option_value(value)
value.to_s
end
end
18 changes: 18 additions & 0 deletions lib/rack/tracker/google_analytics4/template/google_analytics4.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<% if tracker %>
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= tracker %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', "<%= tracker %>");
</script>

<script type="text/javascript">
<% events.each do |var| %>
gtag('event', "<%= var.category %>", {
action: "<%= var.action %>"
});
<% end %>
</script>
<% end %>