Coder Social home page Coder Social logo

tpitale / staccato Goto Github PK

View Code? Open in Web Editor NEW
389.0 13.0 44.0 196 KB

Ruby library to perform server-side tracking into the official Google Analytics Measurement Protocol

License: MIT License

Ruby 99.84% Shell 0.16%
ruby google-analytics analytics analytics-tracking analytics-api

staccato's Introduction

Staccato

Ruby library to track into the official Google Analytics Measurement Protocol

https://developers.google.com/analytics/devguides/collection/protocol/v1/

NOTE: The Measurement Protocol is part of Universal Analytics, which is currently available in public beta. Data from the measurement protocol will only be processed in Universal Analytics enabled properties.

Gem Version Build Status Code Climate

If you're using Rails and would like to use Staccato, we have an gem for that! Staccato Rails

Installation

Add this line to your application's Gemfile:

gem 'staccato'

And then execute:

$ bundle

Or install it yourself as:

$ gem install staccato

Usage

tracker = Staccato.tracker('UA-XXXX-Y') # REQUIRED, your Google Analytics Tracking ID

#tracker optionally takes a second param for the client_id value. By default, the client_id is set to a random UUID with SecureRandom.uuid

Setting SSL on a tracker

# passing nil as the second argument lets Staccato build the client id, as the default
tracker = Staccato.tracker('UA-XXXX-Y', nil, ssl: true)

Track some data

# Track a Pageview (all values optional)
tracker.pageview(path: '/page-path', hostname: 'mysite.com', title: 'A Page!')

# Track an Event (all values optional)
tracker.event(category: 'video', action: 'play', label: 'cars', value: 1)

# Track social activity (all values REQUIRED)
tracker.social(action: 'like', network: 'facebook', target: '/something')

# Track exceptions (all values optional)
tracker.exception(description: 'RuntimeException', fatal: true)

# Track timing (all values optional, but should include time)
tracker.timing(category: 'runtime', variable: 'db', label: 'query', time: 50) # time in milliseconds

tracker.timing(category: 'runtime', variable: 'db', label: 'query') do
  some_code_here
end

# Track transaction (transaction_id REQUIRED)
tracker.transaction({
  transaction_id: 12345,
  affiliation: 'clothing',
  revenue: 17.98,
  shipping: 2.00,
  tax: 2.50,
  currency: 'EUR'
})

# Track transaction item (matching transaction_id and item name REQUIRED)
tracker.transaction_item({
  transaction_id: 12345,
  name: 'Shirt',
  price: 8.99,
  quantity: 2,
  code: 'afhcka1230',
  variation: 'red',
  currency: 'EUR'
})

Building Hits

If you need access to a hit, you can use tracker.build_<hit type> and pass it the same options as the above tracker methods. For example, these are all the same:

# build and track a Staccato::Pageview in a single step
tracker.pageview(options_hash)

# build, and then track, a pageview
tracker.build_pageview(options_hash).track!

# build a Staccato::Pageview, then track it
hit = Staccato::Pageview.new(tracker, options_hash)
hit.track!

"Global" Options

Any of the options on the parameters list (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters) that are accepted on ALL hit types can be set as options on any of the hits.

tracker.pageview(path: '/video/1235', flash_version: 'v1.2.3')

Flash Version is a global option in the example above.

Note: There are a few options that if used will override global options:

  • document_path: overriden by path in pageviews
  • document_hostname: overriden by hostname in pageviews
  • document_title: overriden by title in pageviews

These are holdovers from the original design, where pageview is a hit type that can take any/all of the optional parameters. path, hostname, and title are slightly nicer to use on pageview.

The complete list at this time:

Staccato::Hit::GLOBAL_OPTIONS.keys # =>

[:anonymize_ip,
 :queue_time,
 :data_source,
 :cache_buster,
 :user_id,
 :user_ip,
 :user_agent,
 :referrer,
 :campaign_name,
 :campaign_source,
 :campaign_medium,
 :campaign_keyword,
 :campaign_content,
 :campaign_id,
 :adwords_id,
 :display_ads_id,
 :screen_resolution,
 :viewport_size,
 :screen_colors,
 :user_language,
 :java_enabled,
 :flash_version,
 :document_location,
 :document_encoding,
 :document_hostname,
 :document_path,
 :document_title,
 :link_id,
 :application_name,
 :application_version,
 :application_id,
 :application_installer_id,
 :experiment_id,
 :experiment_variant,
 :product_action,
 :product_action_list,
 :promotion_action,
 :geographical_id]

Boolean options like anonymize_ip will be converted from true/false into 1/0 as per the tracking API docs.

The data_source option can take any value, but note that hits sent from other Google tools will have specific values. Hits sent from analytics.js will have data_source set to web, and hits sent from one of the mobile SDKs will have data_source set to app.

Custom Dimensions and Metrics

hit = Staccato::Pageview.new(tracker, hostname: 'mysite.com', path: '/sports-page-5', title: 'Sports Page #5')
hit.add_custom_dimension(19, 'Sports')
hit.add_custom_metric(2, 5)
hit.track!

The first argument is the slot position. Custom dimensions and metrics have 20 slots or 200 if you're "Premium" account.

The second argument is the value. For dimensions, that's a text value. For metrics it is an integer.

Non-Interactive Hit

# Track a Non-Interactive Hit
tracker.event(category: 'video', action: 'play', non_interactive: true)

Non-Interactive events are useful for tracking things like emails sent, or other events that are not directly the result of a user's interaction.

The option non_interactive is accepted for all methods on tracker.

Session Control

# start a session
tracker.pageview(path: '/blog', start_session: true)

# end a session
tracker.pageview(path: '/blog', end_session: true)

Other options are acceptable to start and end a session: session_start, session_end, and stop_session.

Content Experiment

# Tracking an Experiment
#   useful for tracking A/B or Multivariate testing
tracker.pageview({
  path: '/blog',
  experiment_id: 'a7a8d91df',
  experiment_variant: 'a'
})

Tracker Hit Defaults

Global parameters can be set as defaults on the tracker, and will be used for all hits (unless overwritten by parameters set directly on a hit).

The following example creates a tracker with a default hostname. The two pageviews will track the default hostname and the page path passed in.

tracker = Staccato.tracker('UA-XXXX-Y', client_id, {document_hostname: 'example.com'})

tracker.pageview(path: '/videos/123')
tracker.pageview(path: '/videos/987')

Additional Measurements

Additional Measurements can be added to any Hit type, but most commonly used with pageviews or events. The current set of measurements is for handling Enhanced Ecommerce measurements. I've grouped these into ImpressionList, Product, ProductImpression, Promotion, Transaction, Checkout, and CheckoutOption (w/ ImpressionList). Each can be added and combined – per Google's documentation – onto an existing Hit.

Note: Certain Measurements require an index. This is an integer (usually) between 1 and 200 inclusive.

Note: Certain Measurements require a product_action to be set. This is a global option, and should be set on the original hit. The product_action can be any one of:

  • detail
  • click
  • add
  • remove
  • checkout
  • checkout_option
  • purchase
  • refund

Transaction w/ Product

Using a pageview to track a transaction with a product (using the 'purchase' as the product_action:

pageview = tracker.build_pageview(path: '/receipt', hostname: 'mystore.com', title: 'Your Receipt', product_action: 'purchase')

pageview.add_measurement(:transaction, {
  transaction_id: 'T12345',
  affiliation: 'Your Store',
  revenue: 37.39,
  tax: 2.85,
  shipping: 5.34,
  currency: 'USD',
  coupon_code: 'SUMMERSALE'
})

pageview.add_measurement(:product, {
  index: 1, # this is our first product, value may be 1-200
  id: 'P12345',
  name: 'T-Shirt',
  category: 'Apparel',
  brand: 'Your Brand',
  variant: 'Purple',
  quantity: 2,
  position: 1,
  price: 14.60,
  coupon_code: 'ILUVTEES'
})

pageview.track!

Transaction Refund

The combination of product_action: 'refund' and transaction measurement setting a matching id to a previous transaction.

event = tracker.build_event(category: 'order', action: 'refund', non_interactive: true, product_action: 'refund')

event.add_measurement(:transaction, transaction_id: 'T12345')

event.track!

Transaction & Product Refund

The combination of product_action: 'refund' and transaction measurement setting a matching id to a previous transaction. You can also specify a product (or products, using index) with a quantity (for partial refunds) to refund.

event = tracker.build_event(category: 'order', action: 'refund', non_interactive: true, product_action: 'refund')

event.add_measurement(:transaction, transaction_id: 'T12345')
event.add_measurement(:product, index: 1, id: 'P12345', quantity: 1)

event.track!

Promotion Impression

pageview = tracker.build_pageview(path: '/search', hostname: 'mystore.com', title: 'Search Results')

pageview.add_measurement(:promotion, {
  index: 1,
  id: 'PROMO_1234',
  name: 'Summer Sale',
  creative: 'summer_sale_banner',
  position: 'banner_1'
})

pageview.track!

Promotion Click

Promotion also supports a promotion_action, similar to product_action. This is another global option on Hit.

event = tracker.build_event(category: 'promotions', action: 'click', label: 'internal', promotion_action: 'click')

event.add_measurement(:promotion, {
  index: 1,
  id: 'PROMO_1234',
  name: 'Summer Sale',
  creative: 'summer_sale_banner',
  position: 'banner_1'
})

event.track!

Product Click

event = tracker.build_event(category: 'search', action: 'click', label: 'results', product_action: 'click', product_action_list: 'Search Results')

event.add_measurement(:product, {
  index: 1,
  id: 'P12345',
  name: 'T-Shirt',
  category: 'Apparel',
  brand: 'Your Brand',
  variant: 'Purple',
  quantity: 2,
  position: 1,
  price: 14.60,
  coupon_code: 'ILUVTEES'
})

event.track!

Checkout

pageview = tracker.build_pageview(path: '/checkout', hostname: 'mystore.com', title: 'Complete Your Checkout', product_action: 'checkout')

pageview.add_measurement(:product, {
  index: 1, # this is our first product, value may be 1-200
  id: 'P12345',
  name: 'T-Shirt',
  category: 'Apparel',
  brand: 'Your Brand',
  variant: 'Purple',
  quantity: 2,
  position: 1,
  price: 14.60,
  coupon_code: 'ILUVTEES'
})

pageview.add_measurement(:checkout, {
  step: 1,
  step_option: 'Visa'
})

pageview.track!

Checkout Option

event = tracker.build_event(category: 'checkout', action: 'option', non_interactive: true, product_action: 'checkout_option')

event.add_measurement(:checkout_options, {
  step: 2,
  step_option: 'Fedex'
})

event.track!

Impression List & Product Impression

pageview = tracker.build_pageview(path: '/home', hostname: 'mystore.com', title: 'Home Page')

pageview.add_measurement(:impression_list, index: 1, name: 'Search Results')

pageview.add_measurement(:product_impression, {
  index: 1,
  list_index: 1, # match the impression_list above
  id: 'P12345',
  name: 'T-Shirt',
  category: 'Apparel',
  brand: 'Your Brand',
  variant: 'Purple',
  position: 1,
  price: 14.60
})

pageview.add_measurement(:impression_list, index: 2, name: 'Recommendations')

pageview.add_measurement(:product_impression, {
  index: 1,
  list_index: 2,
  name: 'Yellow Tee'
})

pageview.add_measurement(:product_impression, {
  index: 2,
  list_index: 2,
  name: 'Red Tee'
})

pageview.track!

Screenview (as in mobile)

tracker.screenview({
  screen_name: 'user1'
})

Google Documentation

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide https://developers.google.com/analytics/devguides/collection/protocol/v1/reference https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

Adapters

Staccato provides a variety of adapters for sending or debugging requests being made. To use them, first require the adapter by name: require 'staccato/adapter/#{chosen-adapter-name}'

Multiple adapters can be used by calling add_adapter:

require 'staccato/adapter/validate'

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.add_adapter Staccato::Adapter::Validate.new
  c.add_adapter Staccato::Adapter::Logger.new(Staccato.ga_collection_uri)
  c.add_adapter Staccato::Adapter::Faraday.new(Staccato.ga_collection_uri)
end

Results returned will be in an array, as returned by each adapter in the order the adapters were added.

HTTP Adapters

Staccato provides a number of basic adapters to different ruby http libraries. By default, Staccato uses net/http when you create a new tracker. If you are using Faraday or The Ruby HTTP library Staccato provides adapters.

require 'staccato/adapter/faraday' # Faraday gem must be installed

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = Staccato::Adapter::Faraday.new(Staccato.ga_collection_uri) do |faraday|
    # further faraday configuration here
  end
end

You can also make your own Adapters by implementing any class that responds to post with a hash of params/data to be posted. The default adapters all accept the URI in the initializer, but this is not a requirement for yours.

One such example might be for a new net/http adapter which accepts more options for configuring the connection:

class CustomAdapter
  attr_reader :uri

  def initialize(uri, options={})
    @uri = uri
    @options = options
  end

  def post(data)
    Net::HTTP::Post.new(uri.request_uri).tap do |request|
      request.read_timeout = @options.fetch(:read_timeout, 90)
      request.form_data = data

      execute(request)
    end
  end

  private
  def execute(request)
    Net::HTTP.new(uri.hostname, uri.port).start do |http|
      http.open_timeout = @options.fetch(:open_timeout, 90)
      http.request(request)
    end
  end
end

Which would be used like:

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = CustomAdapter.new(Staccato.ga_collection_uri, read_timeout: 1, open_time: 1)
end

Validation Adapter

The validation adapter sends hits to the debug endpoint, which responds with information about the validity of the hit.

require 'staccato/adapter/validate'

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = Staccato::Adapter::Validate.new
end

See results by printing a call to track any hit:

puts tracker.pageview(path: '/')

By default, the staccato default_adapter is used to send validation hits, but a different adapter can be used (e.g. Faraday or Net::HTTP).

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = Staccato::Adapter::Validate.new(Staccato::Adapter::HTTP)
end

UDP Adapter for Staccato::Proxy

If you're using Staccato::Proxy, you can point Staccato at it using the UDP adapter.

require 'staccato/adapter/udp'

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = Staccato::Adapter::UDP.new(URI('udp://127.0.0.1:3003'))
end

Be sure to set the ip or host and port to wherever you have configured Staccato::Proxy to run.

Logger Adapter for Local Development/Debugging

If you're running in development and simply want to make sure Staccato is being called where you expect it to be. Or, if you want to compare the parameters staccato sends with the Google Analytics documentation.

require 'staccato/adapter/logger'

tracker = Staccato.tracker('UA-XXXX-Y') do |c|
  c.adapter = Staccato::Adapter::Logger.new(Staccato.ga_collection_uri, Logger.new(STDOUT), lambda {|params| JSON.dump(params)})
end

If you would prefer to log to a file (default is STDOUT), you can pass in an instance of a Logger (from Ruby's stdlib) or anything that responds to debug.

If you would like to format the params hash as something other than k=v in your logs, you can pass in anything that responds to call and format as a string. The default should be consumable by Splunk and other logging software.

Image URL for Email Open Tracking

As per google's docs an Event hit type (suggested) may be used to generate an image tag in an email (e.g., as sent by Rails' mailers). This is useful for tracking open stats alongside your other analytics.

Things to keep in mind from Google's suggestions:

  1. Hit type should be Event
  2. category should be 'email'
  3. action should be 'open'
  4. document path should be the type of email, e.g., 'welcome' or 'invite', etc must start with a '/' and is advised to include some scope such as '/email' to make it easier to find
  5. document title should be the subject of the email
  6. set the user id, if it is known; NEVER set the user's email
  7. system info fields may be included if known

To create a url for a hit:

event = tracker.build_event({
  category: 'email',
  action: 'open',
  document_path: '/email/welcome',
  document_title: 'Welcome to Our Website!'
})

# use the image url in your rails template in an image tag
image_url = Staccato.as_url(event)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

staccato's People

Contributors

ajsharma avatar arturoherrero avatar cavi21 avatar martin1keogh avatar naari3 avatar nevans avatar olerichter00 avatar poshe avatar rickyhanna avatar snow avatar thbar avatar tpitale avatar tyler-murphy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

staccato's Issues

Unable to send user_id with pageview and transaction.

Steps to reproduce:

tracker = Staccato.tracker('UA-XXXX-Y', nil, ssl: true)
pageview = tracker.build_pageview(path: '/receipt', title: 'Receipt', product_action: 'purchase')
measurement_params = {user_id: 123, transaction_id: 456, revenue: 10, currency: 'GBP', affiliation: 'My Store'}
pageview.add_measurement(:transaction, measurement_params)

Staccato.as_url(pageview)

=> https://www.google-analytics.com/collect?v=1&tid=UA-XXXX-Y&cid=9c74c068-0eed-43cb-9db1-7066214402ec&t=pageview&pa=purchase&dp=%2Freceipt&dt=Receipt&ti=456&ta=My+Store&tr=10&cu=GBP

The URL does not have the parameter uid.

Enhanced ecommerce?

Hey there, have been trying to use the gem to push some transaction information to Universal Analytics - I need to push transaction and refund data. I've created a transaction with build_transaction then added measurements for the transaction info and product but we're not getting any product info coming through in GA? Can we mimic this https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions
using staccato?

Thanks for any help.

Support for Enhanced Ecommerce Parameters

I was trying to figure out how to extend staccato to support refunds but am somewhat confused.

The refund docs are here:
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#enhancedecom

under "Measuring Refunds"

I was unclear how to create a class that would do the right thing. My first stab looked something like this

      module Staccato
        class Refund
          include Staccato::Hit
          FIELDS = {
            transaction_id: 'ti',
          }

          def type
            :transaction # what goes here? how does stacatto know refunds vs purchases
          end
        end
      end

Logging causing an error

When trying this code to take a look at what staccato is outputting

tracker = Staccato.tracker('UA-XXXX-Y') do |c| c.adapter = Staccato::Adapter::Logger.new(Stacatto.ga_collection_uri, Logger.new(STDOUT), lambda {|params| JSON.dump(params)}) end

You get the following error:
uninitialized constant Staccato::Adapter

Unable to update to the latest version

For some reason the latest version of the solution cannot be updated with a bundle install

gem 'staccato', :git => 'https://github.com/medullan/staccato.git'
returns 0.0.4 only

These do not work:

gem 'staccato', :git => 'https://github.com/medullan/staccato.git', :tag => '0.1.0'

nor

gem 'staccato', :git => 'https://github.com/medullan/staccato.git', :tag => '0.1.o'

However these do work

staccato', :git => 'https://github.com/medullan/staccato.git', :tag => '0.0.3' and '0.0.4'

seems something happened after version 0.0.4

If I clone the repo and manually build the gem and install it, that works but only on Ubuntu. It doesn't work on windows which is where I need it. v0.0.4 does work on windows.

Please advise?

Add optional params to tracking

Unrecognized paramteter '_anon_uip' found.

When I try to run the following code:

require 'staccato'
require 'staccato/adapter/logger'
require 'staccato/adapter/validate'

tracker = Staccato.tracker('UA-XXXXXXXX-Y') do |c|
  c.adapter = Staccato::Adapter::Validate.new
end

puts tracker.pageview(path: '/', user_ip: '127.0.0.1')

I get the following output:

{
  "hitParsingResult": [ {
    "valid": true,
    "parserMessage": [ {
      "messageType": "INFO",
      "description": "Unrecognized paramteter '_anon_uip' found.",
      "messageCode": "UNKNOWN_PARAMETER",
      "parameter": "_anon_uip"
    } ],
    "hit": "/debug/collect?v=1\u0026tid=UA-11773596-2\u0026cid=4a767679-46ac-41b4-a6b4-898b5cf8c50f\u0026t=pageview\u0026uip=xxxxxxxxx\u0026dp=/\u0026_anon_uip=127.0.0.0"
  } ],
  "parserMessage": [ {
    "messageType": "INFO",
    "description": "Found 1 hit in the request."
  } ]
}

It started happening on 18th Nov 2016 - looks like a change in GA API.

Accept unaliased attributes

If folks pass in a string key that isn't an alias, pass it on to google. For new attributes we haven't added to staccato yet.

Rack middleware

It would be great to be able to easily add rack middleware to get pageview tracking information with this gem.

Do you think it would make sense to include this?

I have something like the following at the moment:

class StaccatoRack
  def initialize(app)
    @app = app
  end

  def call(env)
    track_pageview(env)
    @app.call(env)
  end

  def track_pageview(env)
    host = env["HTTP_HOST"]
    path = env["PATH_INFO"]
    tracker.pageview(path: path, hostname: host)
  end

  def tracker
    @tracker ||= Staccato.tracker(ENV["GA_ANALYTICS_ID"])
  end
end

Allow setting global options as defaults on a tracker

Allow setting tracker-level default options for any of the global hit options. Something like this, maybe?

Staccato.tracker('UA-XXXX-Y', hit_defaults: {
  hostname: 'api.example.com',
  adwords_id: 'CL6Q-OXyqKUCFcgK2goddQuoHg'
})

Google Analytic hits show the incorrect location

Hi,

I begin to use stacato for my Rails App, and i have all tame the same issue.
When a event is fired that automaticaly add a user in the realtime dashboard (in the screen you can see 4 users, but only 3 active pages), the adding visit seems located from Ashburn (USA) .
Is not a GA error, because i already have 30 visitors on GA realtime dashboard whereas in reality just 2 visitors were on the site.
image

My code:
Model User for track signup

class User < ApplicationRecord
   after_create :tracking_user_signup

   def tracking_user_signup
      tracker = Staccato.tracker('UA-XXXXXXX-X', nil, ssl: true)
      tracker.event(category: 'User', action: 'Signup', label: "Signup", value: nil)
   end
end

The event is well fired on GA:
image

So, any idea?
Thx

Not seeing events in Google Analytics

Hi! Thanks for the awesome library! I'm having an issue and can't seem to get around it.

I set up a new "mobile app" in the Google Analytics admin panel, got the tracking id (e.g. UA-ABCDEFGH-1), added staccato to a Sinatra project, and am tracking events. Commit is here.

I then go to the Google Analytics site, but don't see any events there.

Am I missing something? Thank you!

ERR_TOO_MANY_REDIRECTS

Issue originally posted in the staccoto-rails gem: tpitale/staccato-rails#11

Reissued here:
This is the first that I have installed this gem. This is not happening on my local when I am loading the page that I am trying to have events tracked, but when I push to our staging environment and I load the page where the tracker has been placed, it redirects at the code:
tracker.event(category: 'staging', action: 'index', label: 'test', value: 1)

batching

supporting batch events using a buffer pattern would be a nice addition to this library.

You're missing the screenview hit type

Logging tracker

Like Noop, but logs to something like STDOUT or Rails.logger.

Multiple products quantity

I have a problem when creating pageview for one transaction and 4 products with quantity 1.
For some reason it creates 4 products with quantity 2, and 8 in total for transaction.

pageview = tracker.build_pageview(path: '/receipt', hostname: 'test.com',
                                      title: 'Money', product_action: 'purchase')
    pageview.add_measurement(:transaction, transaction_params)
    products.each_with_index do |product, index|
      index += 1
      transaction_item = { index: index, id: "1-#{product.id}",
                           name: product.name,
                           price: product.price,
                           quantity: 1,
                           position: index,
                           category: product.url_alias }
      pageview.add_measurement(:product, transaction_item)
 end
    pageview.track!

Default adapter doesn't raise on error?

While writing a test for an app, I realised that:

stub_request(:post, "https://ssl.google-analytics.com/collect").to_return(status: 500, body: "", headers: {})

would not raise an error.

What would be the best strategy to get an error (to e.g. retry in sidekiq) in case the POST failed? (maybe using a custom adapter?)

Multiple adapters?

I'm currently trying to debug a production issue (tracked pageviews aren't showing up in my GA account), but it seems I can either log, OR send the pageview.

Perhaps it would make sense to allow multiple adapters, with the ability to post to all of them? I also don't get the point of the ValidateAdapter, since there is no way to see the output (I thought that was the whole point of sending to the GA debug endpoint)?

Other than that, any help with debugging missing pageviews would be greatly appreciated (when I log, things look fine).

Asynchronously track: what should I use?

Hello,

Just started using this gem today. Great work on it!

What do people usually use to run the tracker asynchronously? I found a ticket suggesting using a HTTP adapter that supports it (#43), but I would like to know if there would be any downside on integrating staccato with sucker_punch (already used on my project), for example. Would there be any interest on integrating it with staccato? I can try to work on that.

Thank you

Support for ruby 1.8

I don't know if it's against the planned roadmap for this gem, but it looks like staccato could perfectly work in ruby 1.8 if the Ruby 1.9 hash syntax is ditched, basically moving from this:

GLOBAL_OPTIONS = {
  anonymize_ip: 'aip', # boolean
  queue_time: 'qt', # integer
  cache_buster: 'z',
  user_id: 'uid', # a known user's id
}

to this:

GLOBAL_OPTIONS = {
  :anonymize_ip => 'aip', # boolean
  :queue_time => 'qt', # integer
  :cache_buster => 'z',
  :user_id => 'uid', # a known user's id
}

Given the main use of these hashes is to server as configuration settings and the fact that this gem is not relaying in any specific Ruby +1.9 feature or in any gem that requires Ruby +1.9, I think it makes sense to remove this constrain without losing legibility and increasing its adoption.

@tpitale Let me know what you think about it… and if you like the change I'll submit a pull request.

Build README

Include links to google docs
Include configuration options and getting started
Include primary usage:

Tracker.pageview('page-path', {})
Tracker.event('event-name')

How to set SSL?

url = (ssl ? 'https://ssl' : 'http://www') + '.google-analytics.com/collect'

There appears to be a way to pass in an ssl attribute into this method but no public way to configure stacatto to use SSL. Is it defaulting to non-SSL google analytics access? Not clear from reading the code. Wanted to bring this up for discussion before doing any kind of work.

add_adapter

I'm using 0.5.1 from rubbygems and getting this undefined method 'add_adapter' for #<Staccato::Tracker:0x00007fa1a3d1a7a8> from

      Staccato.tracker(tracking_id, client_id) do |c|
        c.add_adapter Staccato::Adapter::Logger.new(Staccato.ga_collection_uri, Rails.logger)
        c.add_adapter Staccato::Adapter::Faraday.new(Staccato.ga_collection_uri)
      end

I don't see add_adapter anywhere in the source of that download, though it is in master.
That's pretty weird. Something happen on publish?

Requests in background-jobs

It seems that staccato currently halts the server while sending the request to GA. Is there any reason for this or is requests in another thread something worth considering?

`Staccato.as_url` does not honour tracker SSL setting

Just found this odd behaviour while debugging:

tracker = Staccato.tracker('UA-XXXX-Y', nil, ssl: true)   # => @ssl=true
event = tracker.build_event(category: 'video', action: 'play', label: 'cars', value: 1)   # => @ssl=true
Staccato.as_url(event)
# => "http://www.google-analytics.com/collect?v=1&tid=UA-XXXX-Y&..."

IMO, the expected behaviour is Staccato.as_url to honour the SSL setting and return a "https://sss.google-analytics.com" based URL.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.