kangguru / rack-google-analytics

Simple Rack middleware for implementing google analytics tracking in your Ruby-Rack based project. Supports synchronous and asynchronous insertion and configurable load options
MIT License
257 stars 53 forks source link

Lambda-based tracking code support #36

Closed mbarnett closed 10 years ago

mbarnett commented 10 years ago

We had a set of scenarios in which we wanted an application to be able dynamically specify the tracking code based on whatever business logic needed to govern it. This PR adds support for optionally passing a lambda that provides the tracking code at runtime based on the Rack environment.

With this change a site can define a tracker like

 config.middleware.use Rack::GoogleAnalytics, :tracker => lambda { |env| 
  return env[:site_ga].tracker if env[:site_ga]
}

and then vary the tracking code dynamically based on whatever logic it wants, a contrived example being:

class WelcomeController < ApplicationController
  def index
    env[:site_ga] = OpenStruct.new(:tracker => "abc123")
  end
end