lib/mixpanel/tracker/middleware.rb in mixpanel-1.0.0 vs lib/mixpanel/tracker/middleware.rb in mixpanel-1.1.1
- old
+ new
@@ -5,32 +5,35 @@
class Middleware
def initialize(app, mixpanel_token, options={})
@app = app
@token = mixpanel_token
@options = {
- :async => false
+ :async => false,
+ :insert_js_last => false
}.merge(options)
end
def call(env)
@env = env
@status, @headers, @response = @app.call(env)
- update_response!
- update_content_length!
- delete_event_queue!
+ if is_trackable_response?
+ update_response!
+ update_content_length!
+ delete_event_queue!
+ end
[@status, @headers, @response]
end
private
def update_response!
@response.each do |part|
if is_regular_request? && is_html_response?
- insert_at = part.index('</head')
+ insert_at = part.index(@options[:insert_js_last] ? '</body' : '</head')
unless insert_at.nil?
part.insert(insert_at, render_event_tracking_scripts) unless queue.empty?
part.insert(insert_at, render_mixpanel_scripts) #This will insert the mixpanel initialization code before the queue of tracking events.
end
elsif is_ajax_request? && is_html_response?
@@ -59,9 +62,13 @@
@headers["Content-Type"].include?("text/html") if @headers.has_key?("Content-Type")
end
def is_javascript_response?
@headers["Content-Type"].include?("text/javascript") if @headers.has_key?("Content-Type")
+ end
+
+ def is_trackable_response?
+ is_html_response? || is_javascript_response?
end
def render_mixpanel_scripts
if @options[:async]
<<-EOT