Class: Bacchanalytics::WebsiteOptimizer

Inherits:
Object
  • Object
show all
Includes:
GoogleAnalytics::Base, WebsiteOptimizerTrackingCode
Defined in:
lib/bacchanalytics/website_optimizer.rb

Instance Method Summary collapse

Methods included from WebsiteOptimizerTrackingCode

#website_optimizer_tracking_code

Methods included from GoogleAnalytics::Base

#response_source, #should_instrument?

Constructor Details

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

Returns a new instance of WebsiteOptimizer.



168
169
170
171
172
173
# File 'lib/bacchanalytics/website_optimizer.rb', line 168

def initialize(app, options = {})
  @app = app
  @account_id = options[:account_id] || "UA-XXXXX-X"
  @ab = options[:ab] || {}
  @skip_ga_src = options[:skip_ga_src] || false
end

Instance Method Details

#call(env) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/bacchanalytics/website_optimizer.rb', line 175

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

  if should_instrument?(headers) && (source = response_source(response))
    page = env['REQUEST_URI']
    page.gsub!(/\?.*/, '') if page #remove url parameters

    @skip_ga_src = true if env["bacchanalytics.loaded_ga_src"]
    tracking_code = website_optimizer_tracking_code(page, @account_id, @ab)
    return [status, headers, response] if tracking_code.to_s == ""

    env["bacchanalytics.loaded_ga_src"] = true
    new_body = source.sub /<[hH][eE][aA][dD]\s*>/, "<head>\n\n#{tracking_code}"
    headers["Content-Length"] = new_body.length.to_s
    Rack::Response.new(new_body, status, headers).finish
  else
    [status, headers, response]
  end
end