Class: Rack::GoogleAnalytics

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/version.rb,
lib/rack/google-analytics.rb,
lib/rack/google-analytics/version.rb

Constant Summary collapse

VERSION =
'0.12.0'
EVENT_TRACKING_KEY =
"google_analytics.event_tracking"
DEFAULT =
{ :async => true }

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ GoogleAnalytics

Returns a new instance of GoogleAnalytics.

Raises:

  • (ArgumentError)


12
13
14
15
# File 'lib/rack/google-analytics.rb', line 12

def initialize(app, options = {})
  raise ArgumentError, "Tracker must be set!" unless options[:tracker] and !options[:tracker].empty?
  @app, @options = app, DEFAULT.merge(options)
end

Instance Method Details

#_call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rack/google-analytics.rb', line 19

def _call(env)
  @status, @headers, @body = @app.call(env)
  return [@status, @headers, @body] unless html?
  response = Rack::Response.new([], @status, @headers)
  @options[:tracker_vars] = env["google_analytics.custom_vars"] || []

  if response.ok?
    # Write out the events now
    @options[:tracker_vars] += (env[EVENT_TRACKING_KEY]) unless env[EVENT_TRACKING_KEY].nil?

    # Get any stored events from a redirection
    session = env["rack.session"]
    stored_events = session.delete(EVENT_TRACKING_KEY) if session
    @options[:tracker_vars] += stored_events unless stored_events.nil?
  elsif response.redirection?
    # Store the events until next time
    env["rack.session"][EVENT_TRACKING_KEY] = env[EVENT_TRACKING_KEY]
  end

  @body.each { |fragment| response.write inject(fragment) }
  @body.close if @body.respond_to?(:close)
  
  response.finish
end

#call(env) ⇒ Object



17
# File 'lib/rack/google-analytics.rb', line 17

def call(env); dup._call(env); end