Class: GaEvents::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/ga_events/middleware.rb

Constant Summary collapse

SESSION_GA_EVENTS_KEY =
'ga_events.events'

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



9
10
11
# File 'lib/ga_events/middleware.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ga_events/middleware.rb', line 13

def call(env)
  init_event_list(env)
  status, headers, response = @app.call(env)

  headers = Rack::Utils::HeaderHash.new(headers)
  if GaEvents::List.present?
    request = Rack::Request.new(env)

    # Can outgrow, headers might get too big
    serialized = GaEvents::List.to_s
    if xhr_or_turbolinks?(request)
      # AJAX request
      headers['x-ga-events'] = CGI.escapeURIComponent(serialized)
    elsif redirect?(status)
      # 30x/redirect? Then add event list to rack session to survive the
      # redirect.
      add_events_to_session(env, serialized)
    elsif html?(status, headers)
      response = inject_div(response, serialized)
    end
  end

  [status, headers, response]
end