Rack::GaTrack
Rack::GaTrack is a rack middleware that extracts Google Analytics Campaign params from the request. Specifically, it looks for a param utm_source in the request. If found, it creates a cookie with utm_source, utm_content, utm_term, utm_campaign,landing_page (path), referer, and time. Anytime utm_source is found in the request the cookie will be updated with the new Google Analytics Campaign params.
Use Case
Let's say you want to track signups in your app from a specific campaign.
- A user clicks a link on an external site that has your Google Analytics Campaign params in the request.
- Rack::GaTrack finds utm_source param in the request and parses the other Google Analytics Campaign params from the request and saves them in a cookie.
- If a user signs up now or in the future you can read the Google Analytics Campaign params from the env variables that Rack::GaTrack creates and save them to the created user record.
Installation
gem install rack-ga-track
Rails 4 Example Usage
Add the Rack::GaTrack to your application stack:
#Rails 4 in config/application.rb
class Application < Rails::Application
config.middleware.use Rack::GaTrack
end
You can now access your Google Analytics Campaign params in
env['ga_track.source']
env['ga_track.term']
env['ga_track.content']
env['ga_track.campaign']
env['ga_track.medium']
env['ga_track.referer']
env['ga_track.landing_page']
env['ga_track.time']
Customization
By default cookie is set for 30 days, you can extend time to live with :ttl
option (default is 30 days).
#Rails 4 in config/application.rb
class Application < Rails::Application
config.middleware.use Rack::GaTrack, :ttl => 3.months
end
The :domain
option allows to customize cookie domain.
#Rails 4 in config/application.rb
class Application < Rails::Application
config.middleware.use Rack::GaTrack, :domain => '.example.org'
end
Rack::GaTrack will set cookie on .example.org
so it's accessible on www.example.org
, app.example.org
etc.