百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rack-tracker

> 编程语言
开源

跟踪变得简单: 不要费心去为应用添加跟踪和分析部分,而是专注于重要的事情。

648 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

跟踪变得简单: 不要费心去为应用添加跟踪和分析部分,而是专注于重要的事情。

Rack::Tracker

Rationale

Most of the applications we're working on are using some sort of tracking/analytics service, Google Analytics comes first but its likely that more are added as the project grows. Normally you'd go ahead and add some partials to your application that will render out the needed tracking codes. As time passes by you'll find yourself with lots of tracking snippets, that will clutter your codebase :) When just looking at Analytics there are solutions like rack-google-analytics but they just soley tackle the existence of one service.

We wanted a solution that ties all services together in one place and offers an easy interface to drop in new services. This is why we created rack-tracker, a rack middleware that can be hooked up to multiple services and exposing them in a unified fashion. It comes in two parts, the first one is the actual middleware that you can add to the middleware stack the second part are the service-handlers that you're going to use in your application. It's easy to add your own custom handlers, but to get you started we're shipping support for the services mentioned below out of the box:

Respecting the Do Not Track (DNT) HTTP header

The Do Not Track (DNT) HTTP header is a HTTP header that requests the server to disable its tracking of the individual user. This is an opt-out option supported by most browsers. This option is disabled by default and has to be explicitly enabled to indicate the user's request to opt-out. We believe evey application should respect the user's choice to opt-out and respect this HTTP header.

Since version 2.0.0 rack-tracker respects that request header by default. That means NO tracker is injected IF the DNT header is set to "1".

This option can be overwriten using the DO_NOT_RESPECT_DNT_HEADER => true option which must be set on any handler that should ignore the DNT header. (but please think twice before doing that)

Example on how to not respect the DNT header

use Rack::Tracker do
  # this tracker will be injected EVEN IF the DNT header is set to 1
  handler :maybe_a_friendly_tracker, { tracker: 'U-XXXXX-Y', DO_NOT_RESPECT_DNT_HEADER: true }
  # this tracker will NOT be injected if the DNT header is set to 1
  handler :google_analytics, { tracker: 'U-XXXXX-Y' }
end

Further reading on the DNT header:

  • Wikipedia Do Not Track
  • EFF: Do Not Track

Installation

Add this line to your application's Gemfile:

gem 'rack-tracker'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rack-tracker

Usage

Add it to your middleware stack

config.middleware.use(Rack::Tracker) do
  handler :google_analytics, { tracker: 'U-XXXXX-Y' }
end

This will add Google Analytics as a tracking handler.

Sinatra / Rack

You can even use Rack::Tracker with Sinatra or respectively with every Rack application

Just insert the Tracker in your Rack stack:

web = Rack::Builder.new do
  use Rack::Tracker do
    handler :google_analytics, { tracker: 'U-XXXXX-Y' }
  end
  run Sinatra::Web
end

run web

Although you cannot use the Rails controller extensions for obvious reasons, its easy to inject arbitrary events into the request environment.

request.env['tracker'] = {
  'google_analytics' => [
    { 'class_name' => 'Send', 'category' => 'Users', 'action' => 'Login', 'label' => 'Standard' }
  ]
}

Services

Google Global Site Tag (gtag.js)

  • :anonymize_ip - sets the tracker to remove the last octet from all IP addresses, see https://developers.google.com/analytics/devguides/collection/gtagjs/ip-anonymization for details.
  • :cookie_domain - sets the domain name for the GATC cookies. If not set its the website domain, with the www. prefix removed.
  • :user_id - defines a proc to set the userId. Ex: user_id: lambda { |env| env['rack.session']['user_id'] } would return the user_id from the session.
  • :link_attribution - Enables Enhanced Link Attribution.
  • :allow_display_features - Can be used to disable Display Features.
  • :custom_map - Used to Configure and send custom dimensions
  • :optimize_id - Used to Deploy Optimize using gtag
  • :set - Used in the set command to configure multiple properties

Trackers

Google Global Site tag allows configuring multiple trackers. Use the tracker option to configure the ids:

config.middleware.use(Rack::Tracker) do
  handler :google_global, { trackers: [ { id: 'U-XXXXX-Y' }, { id: 'U-WWWWWW-Z'} ] }
end

Google Analytics

  • :anonymize_ip - sets the tracker to remove the last octet from all IP addresses, see https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat?hl=de#_gat._anonymizeIp for details.
  • :cookie_domain - sets the domain name for the GATC cookies. If not set its the website domain, with the www. prefix removed.
  • :user_id - defines a proc to set the userId. Ex: user_id: lambda { |env| env['rack.session']['user_id'] } would return the user_id from the session.
  • :site_speed_sample_rate - Defines a new sample set size for Site Speed data collection, see https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration?hl=de#_gat.GA_Tracker_._setSiteSpeedSampleRate
  • :adjusted_bounce_rate_timeouts - An array of times in seconds that the tracker will use to set timeouts for adjusted bounce rate tracking. See http://analytics.blogspot.ca/2012/07/tracking-adjusted-bounce-rate-in-google.html for details.
  • :enhanced_link_attribution - Enables Enhanced Link Attribution.
  • :advertising - Enables Display Features.
  • :ecommerce - Enables Ecommerce Tracking.
  • :enhanced_ecommerce - Enables Enhanced Ecommerce Tracking
  • :optimize - pass Google Optimize container ID as value (e.g. optimize: 'GTM-1234').
  • :pageview_url_script - a String containing a custom js script evaluating to the url that shoudl be given to the pageview event. Default to window.location.pathname + window.location.search.
  • :explicit_pageview - A boolean that controls whether to send the pageview event on pageload. This defaults to true.

Events

To issue Events from the server side just call the tracker method in your controller.

  def show
    tracker do |t|
      t.google_analytics :send, { type: 'event', category: 'button', action: 'click', label: 'nav-buttons', value: 'X' }
    end
  end

It will render the following to the site source:

  ga('send', { 'hitType': 'event', 'eventCategory': 'button', 'eventAction': 'click', 'eventLabel': 'nav-buttons', 'value': 'X' })

Parameters

You can set parameters in your controller too:

  def show
    tracker do |t|
      t.google_analytics :parameter, { dimension1: 'pink' }
    end
  end

Will render this:

  ga('set', 'dimension1', 'pink');

Enhanced Ecommerce

You can set parameters in your controller:

  def show
    tracker do |t|
      t.google_analytics :enhanced_ecommerce, {
        type: 'addItem',
        id: '1234',
        name: 'Fluffy Pink Bunnies',
        sku: 'DD23444',
        category: 'Party Toys',
        price: '11.99',
        quantity: '1'
      }
    end
  end

Will render this:

  ga("ec:addItem", {"id": "1234", "name": "Fluffy Pink Bunnies", "sku": "DD23444", "category": "Party Toys", "price": "11.99", "quantity": "1"});

Ecommerce

You can even trigger ecommerce directly from within your controller:

  def show
    tracker do |t|
      t.google_analytics :ecommerce, { type: 'addItem', id: '1234', affiliation: 'Acme Clothing', revenue: '11.99', shipping: '5', tax: '1.29' }
    end
  end

Will give you this:

  ga('ecommerce:addItem', { 'id': '1234', 'affiliation': 'Acme Clothing', 'revenue': '11.99', 'shipping': '5', 'tax': '1.29'  })

To load the ecommerce-plugin, add some configuration to the middleware initialization. This is not needed for the above to work, but recommened, so you don't have to take care of the plugin on your own.

  config.middleware.use(Rack::Tracker) do
    handler :google_analytics, { tracker: 'U-XXXXX-Y', ecommerce: true }
  end

Google Adwords Conversion

You can configure the handler with default options:

config.middleware.use(Rack::Tracker) do
  handler :google_adwords_conversion, { id: 123456,
                                        language: "en",
                                        format: "3",
                                        color: "ffffff",
                                        label: "Conversion label",
                                        currency: "USD" }
end

To track adwords conversion from the server side just call the tracker method in your controller.

  def show
    tracker do |t|
      t.google_adwords_conversion :conversion, { value: 10.0 }
    end
  end

You can also specify a different value from default options:

  def show
    tracker do |t|
      t.google_adwords_conversion :conversion, { id: 123456,
                                                 language: 'en',
                                                 format: '3',
                                                 color: 'ffffff',
                                                 label: 'Conversion Label',
                                                 value: 10.0 }
    end
  end

Google Tag Manager

Google Tag manager code snippet supports the container id

  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: 'GTM-XXXXXX' }
  end

You can also use an experimental feature to track pageviews under turbolinks, which adds a pageView event with a virtualUrl of the current url.

  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: 'GTM-XXXXXX', turbolinks: true }
  end

Data Layer

GTM supports a dataLayer for pushing events as well as variables.

To add events or variables to the dataLayer from the server side, just call the tracker method in your controller.

  def show
    tracker do |t|
      t.google_tag_manager :push, { price: 'X', another_variable: ['array', 'values'] }
    end
  end

Facebook

  • Facebook Pixel - adds the Facebook Pixel

Use in conjunction with the

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyecommercefacebookgoogle-analyticsrack

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言