Module: GoogleAnalytics::Rails::ViewHelpers

Defined in:
lib/google-analytics/rails/view_helpers.rb

Overview

All the helper methods output raw javascript with single quoted strings. This allows more flexbility in choosing when the event gets sent (on page load, on user action, etc).

The only exception is #analytics_init, which is wrapped in a <script> tag.

Examples:

This event is always sent on page load


<script>
  <%= analytics_track_event "Videos", "Play", "Gone With the Wind" %>
</script>

This event is sent when the visitor clicks on the link


# note the double quotes around the onclick attribute,
# they are necessary because the javascript is single quoted
<a href="my_url" onclick="<%= analytics_track_event "Videos", "Play", "Gone With the Wind" %>">Link</a>

Full ecommerce example


# create a new transaction
analytics_add_transaction(
  '1234',           # order ID - required
  'Acme Clothing',  # affiliation or store name
  '11.99',          # total - required
  '1.29',           # tax
  '5'               # shipping
  'San Jose',       # city
  'California',     # state or province
  'USA'             # country
)

# add an item to the transaction
analytics_add_item(
  '1234',           # order ID - required
  'DD44',           # SKU/code - required
  'T-Shirt',        # product name
  'Green Medium',   # category or variation
  '11.99',          # unit price - required
  '1'               # quantity - required
)

# submit the transaction
analytics_track_transaction

Instance Method Summary collapse

Instance Method Details

#analytics_add_item(order_id, product_id, product_name, product_variation, unit_price, quantity) ⇒ Object

Add an item to the current transaction



194
195
196
# File 'lib/google-analytics/rails/view_helpers.rb', line 194

def analytics_add_item(order_id, product_id, product_name, product_variation, unit_price, quantity)
  analytics_render_event(GA::Events::Ecommerce::AddItem.new(order_id, product_id, product_name, product_variation, unit_price, quantity))
end

#analytics_add_transaction(order_id, store_name, total, tax, shipping, city, state_or_province, country) ⇒ Object

Track an ecommerce transaction



187
188
189
190
# File 'lib/google-analytics/rails/view_helpers.rb', line 187

def analytics_add_transaction(order_id, store_name, total, tax, shipping, city, state_or_province, country)
  analytics_render_event(GA::Events::Require.new('ecommerce','ecommerce.js'))
  analytics_render_event(GA::Events::Ecommerce::AddTransaction.new(order_id, store_name, total, tax, shipping, city, state_or_province, country))
end

#analytics_init(options = {}) ⇒ String

Initializes the Analytics javascript. Put it in the <head> tag.

Examples:

Set the local bit in development mode

analytics_init :local => Rails.env.development?

Allow links across domains

analytics_init :add_events => Events::SetAllowLinker.new(true)

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

Returns:

  • (String)

    a <script> tag, containing the analytics initialization sequence.



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/google-analytics/rails/view_helpers.rb', line 89

def analytics_init(options = {})
  unless tracker = options.delete(:tracker).presence
    tracker = GA.tracker
    raise ArgumentError, "Tracker must be set! Did you set GA.tracker ?" unless tracker
  end

  local = options.delete(:local) || false
  setup = options.delete(:setup) || {}
  tracker_name = options.delete(:name) || setup.fetch(:name, nil)

  # Determine Name
  setup[:name] ||= tracker_name if tracker_name

  domain = options.delete(:domain) || (local ? "none" : "auto")

  skip_pageview = options.delete(:skip_pageview) || false
  anonymize = options.delete(:anonymize) || false
  custom_vars = options.delete(:custom_vars) || []
  custom_vars = [custom_vars] unless custom_vars.is_a?(Array)

  link_attribution = options.delete(:enhanced_link_attribution) || false


  events = options.delete(:add_events) || []
  events = [events] unless events.is_a?(Array)

  # Convert older classes when we can
  if events.any?{|x| x.class.name == 'GoogleAnalytics::Events::SetAllowLinker' }
    setup[:allowLinker] = !!events.any?{|x| x.class.name == 'GoogleAnalytics::Events::SetAllowLinker' }
    events.delete_if{|x| x.class.name == 'GoogleAnalytics::Events::SetAllowLinker' }
  end

  if events.any?{|x| x.class.name == 'GoogleAnalytics::Events::SetSiteSpeedSampleRate' }
    setup[:siteSpeedSampleRate] = events.select{|x| x.class.name == 'GoogleAnalytics::Events::SetSiteSpeedSampleRate' }.first.sample_rate
    events.delete_if{|x| x.class.name == 'GoogleAnalytics::Events::SetSiteSpeedSampleRate' }
  end

  queue = GAQ.new
  # unshift => reverse order
  events.unshift GA::Events::TrackPageview.new({:page => options[:page], :title => options[:title]}) unless skip_pageview
  # anonymize if needed before tracking the page view
  events.unshift GA::Events::AnonymizeIp.new if anonymize
  # custom_var if needed before tracking the page view
  custom_vars.each do |custom_var|
    events.unshift custom_var
  end

  events.unshift GA::Events::Require.new('linkid') if link_attribution

  # If this is 'local' env, give the cookieDomain none, and allow linker
  if local
    events.unshift GA::Events::SetupAnalytics.new(tracker, setup.merge({
      :cookieDomain => 'none',
      :allowLinker => true
    }))
  # If we have any configs, we'll merge the cookieDomain in
  elsif setup.any?
    events.unshift GA::Events::SetupAnalytics.new(tracker, setup.merge({ :cookieDomain => domain }))
  # Just a normal request
  else
    events.unshift GA::Events::SetupAnalytics.new(tracker, domain)
  end

  events.each do |evt|
    if evt.class.name == 'GoogleAnalytics::Events::SetupAnalytics'
      queue.push(evt)
    else
      queue.push(evt, tracker_name)
    end
  end

  queue.to_s.html_safe
end

#analytics_set_custom_var(index, name, value, opt_scope = 3) ⇒ Object

Set a custom variable. You're allowed only 1-5 for the index. The lifetime is defined by: 1 = visitor-level 2 = session-level 3 = page-level (default)



181
182
183
# File 'lib/google-analytics/rails/view_helpers.rb', line 181

def analytics_set_custom_var(index, name, value, opt_scope = 3)
  analytics_render_event(GA::Events::SetCustomVar.new(index, name, value, opt_scope))
end

#analytics_track_event(category, action, label = nil, value = nil) ⇒ Object

Track a custom event

Examples:


analytics_track_event "Videos", "Play", "Gone With the Wind"

See Also:



170
171
172
# File 'lib/google-analytics/rails/view_helpers.rb', line 170

def analytics_track_event(category, action, label = nil, value = nil)
  analytics_render_event(GA::Events::TrackEvent.new(category, action, label, value))
end

#analytics_track_transactionObject

Flush the current transaction



200
201
202
# File 'lib/google-analytics/rails/view_helpers.rb', line 200

def analytics_track_transaction
  analytics_render_event(GA::Events::Ecommerce::TrackTransaction.new)
end