Sha256: 91ae56ea71c07f2ef5d69ea6c588e18b26cee4de1420445063513f75ca726581

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

class Rack::Tracker::Handler
  class << self
    def process_track(env, method_name, *args, &block)
      new(env).write_event(track(method_name, *args, &block))
    end

    # overwrite me in the handler subclass if you need more control over the event
    def track(name, *event)
      { name.to_s => [event.last.merge('class_name' => event.first.to_s.classify)] }
    end
  end

  class_attribute :position
  self.position = :head

  attr_accessor :options
  attr_accessor :env

  # Allow javascript escaping in view templates
  include Rack::Tracker::JavaScriptHelper

  def initialize(env, options = {})
    self.env = env
    self.options  = options
    self.position = options[:position] if options.has_key?(:position)
  end

  def events
    events = env.fetch('tracker', {})[handler_name] || []
    events.map { |ev| "#{self.class}::#{ev['class_name']}".constantize.new(ev.except('class_name')) }
  end

  def render
    Tilt.new(File.join(File.dirname(__FILE__), handler_name, 'template', "#{handler_name}.erb") ).render(self)
  end

  def inject(response)
    # Sub! is enough, in well formed html there's only one head or body tag.
    # Block syntax need to be used, otherwise backslashes in input will mess the output.
    # @see http://stackoverflow.com/a/4149087/518204 and https://github.com/railslove/rack-tracker/issues/50
    response.sub! %r{</#{self.position}>} do |m|
      self.render << m.to_s
    end
    response
  end

  def write_event(event)
    event.deep_stringify_keys! # for consistent hash access use strings (keys from the session are always strings anyway)
    if env.key?('tracker')
      self.env['tracker'].deep_merge!(event) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
    else
      self.env['tracker'] = event
    end
  end

  def handler_name
    self.class.name.demodulize.underscore
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rack-tracker-1.5.0 lib/rack/tracker/handler.rb