Analytics for Ruby

Our Ruby library lets you record analytics data from your ruby code. The requests hit our servers, and then we route your data to any analytics service you enable on your integrations page. The library is open-source, so you can check it out on Github.

All of our server-side libraries are built for high-performance, so you can use them in your web server controller code. This library uses an internal queue to make identify and track calls non-blocking and fast. It also batches messages and flushes asynchronously to our servers.

If you have any questions, run into any problems or just want to chat about the code, feel free to email us or submit an issue on Github.

Want to stay updated on releases? Subscribe to the release feed.

Getting Started

To get started with our Ruby library check out the quickstart guide which will help you install analytics tracking on your servers in just a few minutes. Once you’ve installed the library, read on for the detailed API reference!

Identify

identify lets you tie a user to their actions and record traits about them.

You’ll want to identify a user with any relevant information as soon as they log-in or sign-up.

Analytics.identify(
    user_id: '019mr8mf4r',
    traits: { email: '#{ user.email }', friends: 872 },
    context: {ip: '8.8.8.8'})
user_id String or NumberThe ID for this user in your database.
anonymous_id String or Number, optionalThe ID associated with the user when you don’t know who they are (either user_id or anonymous_id must be given).
integrations Hash, optionalA Hash specifying which integrations this should be sent to.
traits Hash, optionalA Hash of traits you know about the user. Things like: email, name or friends.
timestamp Time, optionalA Time object representing when the identify took place. This is most useful if you’re importing historical data. If the identify just happened, leave it blank and we’ll use the server’s time.
context Hash, optionalA Hash that can include things like userAgent or ip.

Track

track lets you record the actions your users perform.

You’ll want to track an event whenever the user clicks, taps or submits something in your app.

Analytics.track(
    user_id: '019mr8mf4r',
    event: 'Purchased Item',
    properties: { revenue: 39.95, shipping: '2-day' })
user_id String or NumberThe ID for this user in your database.
event StringThe name of the event you’re tracking. We recommend human-readable names like Played Song or Updated Status.
properties Hash, optionalA Hash of properties for the event. If the event was Added to Cart, it might have properties like price or product.
timestamp DateTime, optionalA DateTime representing when the event took place. If the identify just happened, leave it out and we’ll use the server’s time. If you’re importing data from the past make sure you send a timestamp.
context Hash, optionalA Hash that can include things like userAgent or ip.
anonymous_id String or Number, optionalThe ID associated with the user when you don’t know who they are (either user_id or anonymous_id must be given).
integrations Hash, optionalA Hash specifying which integrations this should be sent to.

Page

The page method lets you record page views on your website, along with optional extra information about the page being viewed.

If you’re using our client-side setup in combination with the Ruby library, page calls are already tracked for you by default. However, if you want to record your own page views manually and aren’t using our client-side library, read on!

Here’s a basic example, along with the page method signature:

Analytics.page(
  user_id: user_id,
  category: 'Docs',
  name: 'Ruby library',
  properties: { url: 'https://segment.com/libraries/ruby/' })
user_id StringThe ID for this user in your database.
category String, optionalThe category of the page. Useful for things like ecommerce where many pages might live under a larger category. Note: if you only pass one string to page we assume it’s a name, not a category. You must include a name if you want to send a category.
name String, optionalThe name of the of the page, for example Signup or Home.
properties Hash, optionalA hash of properties of the page. We’ll automatically send the url, title, referrer and path, but you can add your own too!
anonymous_id String, optionalIf you want to track users anonymously, you can include the Anonymous ID instead of a User ID
context Hash, optionalAn object containing any number of options or context about the request. To see the full reference of supported keys, check them out in the context reference

Alias

alias is how you associate one identity with another. In Mixpanel it’s used to associate an anonymous user with an identified user once they sign up. For KISSmetrics and Trak.io if your user switches IDs, you can use ‘alias’ to rename the ‘user_id’.

This is most frequently needed if you’re using Mixpanel. Read the method docs here.

Analytics.alias(previous_id: 'previous id', user_id: 'new id')

Here’s a full example:

# the anonymous user does actions ...
Analytics.track(user_id: 'anonymous_user', event: 'Anonymous Event')
# the anonymous user signs up and is aliased
Analytics.alias(previous_id: 'anonymous id', user_id: 'user id')
# the identified user is identified
Analytics.identify(user_id: 'user id', traits: { plan: 'Free' })
# the identified user does actions ...
Analytics.track(user_id: 'user id', event: 'Identified Action')

Selecting Integrations

You can specify which analytics integrations you want each call to go to.

Analytics.track({
  user_id: '83489',
  event: 'Paused Song',
  integrations: { all: false, KISSmetrics: true }
})

In this case, we’re specifying that we want this identify to only go to KISSmetrics. all: false says that no integration should be enabled unless otherwise specified. KISSmetrics: true turns on KISSmetrics, etc. To specify an integration, just use it’s formal name (i.e. “AdLearn Open Platform” or “awe.sm”), which is also the title of the integration’s documentation.

Flush

If you’re running any sort of script or internal queue system to upload data, you’ll want to call Analytics.flush at the end of execution to ensure that all messages are sent to our servers.

Analytics.flush

Calling flush will block execution until all messages are processed, so it is not recommended in normal execution of your production application.

If you’re using Ruby on Rails with the Turbolinks setting enabled, and you’re adding Analytics.js on your website, you’ll need to tweak the default configuration.

Instead of having the entire snippet in the <head> of your site, you need to move the analytics.page() call that is included in the snippet by default into the <body> so that it will get triggered on every new page load. But you must have the first part of the snippet in the <head> or the library will fail to load properly.

Performance

Our libraries are built to support high performance environments. That means it is safe to use analytics-ruby on a web server that’s serving hundreds of requests per second.

Every method you call does not result in an HTTP request, but is queued in memory instead. Messages are flushed in batch in the background, which allows for much faster operation.

By default, our library will flush:

  • the very first time it gets a message
  • whenever messages are queued and there is no outstanding request

The queue consumer makes only a single outbound request at a time to avoid saturating your server’s resources. If multiple messages are in the queue, they are sent together in a batch call.

You can specify the following additional options to determine how the queue operates and to help debug possible errors. None of them are required for normal operation.

# Error handler to log statements

Segment::Analytics.new({
  write_key: 'YOUR_WRITE_KEY',
  on_error: Proc.new { |status, msg| print msg },
  max_queue_size: 10000,
  batch_size: 100,
  stub: true
})
on_error Proc, optionalA handler which is called whenever errors are returned from the API. Useful for debugging and first time integrations.
max_queue_size FixNum, optionalThe max number of messages to put in the queue before refusing to queue more (defaults to 10,000).
batch_size FixNum, optionalThe max number of events/identifies to send in a single batch (defaults to 100). The API servers will not respond to messages over a certain size, so 100 is a safe default.
stub TrueClass|FalseClass, optionalIf true, the requests don’t hit the server and are stubbed to be successful (defaults to false).

Multiple Clients

Different parts of your application may require different types of batching, or even sending to multiple Segment projects. In that case, you can initialize multiple instances of Analytics with different settings:

AppAnalytics = Segment::Analytics.new({
  write_key: 'ONE_WRITE_KEY'
})

MarketingAnalytics = Segment::Analytics.new({
  write_key: 'ANOTHER_WRITE_KEY'
})

Troubleshooting

If you’re having trouble we have a few tips that help common problems.

No events in my debugger

  1. Double check that you’ve followed all the steps in the Quickstart.

  2. Make sure that you’re calling one of our API methods once the library is successfully installed—identify, track, etc.

No events in my end tools

  1. Double check your credentials for that integration.

  2. Make sure that the integration you are troubleshooting can accept server-side API calls. Compatibility is shown on the integration docs pages and on the sheets on your Segment project Integrations page:

    Supported platforms

  3. Check out the integration’s documentation to see if there are other requirements for using the method and integration you’re trying to get working.


If you ever have any questions, or see anywhere we can improve our documentation, feel free to contact us!