Class: GaEvents::Middleware
- Inherits:
-
Object
- Object
- GaEvents::Middleware
- Defined in:
- lib/ga_events/middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
5 6 7 |
# File 'lib/ga_events/middleware.rb', line 5 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/ga_events/middleware.rb', line 8 def call(env) # Handle events stored in flash # Parts borrowed from Rails: # https://github.com/rails/rails/blob/v3.2.14/actionpack/lib/action_dispatch/middleware/flash.rb flash = env['rack.session'] && env['rack.session']['flash'] # Fix for Rails 4 flash &&= flash['flashes'] if Rails::VERSION::MAJOR > 3 GaEvents::List.init(flash && flash['ga_events']) 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 request.xhr? # AJAX request headers['X-GA-Events'] = serialized elsif (300..399).include?(status) # 30x/redirect? Then add event list to flash to survive the redirect. flash_hash = env[ActionDispatch::Flash::KEY] flash_hash ||= ActionDispatch::Flash::FlashHash.new flash_hash['ga_events'] = serialized env[ActionDispatch::Flash::KEY] = flash_hash elsif is_html?(status, headers) body = response body = body.each.to_a.join if body.respond_to?(:each) body = body.sub('</body>', "<div data-ga-events='#{serialized}'></div>\\0") response = [body] end end [status, headers, response] end |