Plainflow Ruby Client
Our Ruby library lets you record analytics data from your ruby code.
This 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.
Getting Started
Install the Gem
If you’re using bundler, add the following line to your project’s Gemfile
:
gem 'plainflow', '~> 2.2.3.pre.p1', :require => 'plainflow/analytics'
Or, if you’re using the gem directly from your application, you’ll need to:
gem install plainflow
Then initialize the gem with your Secret Key and an optional error handler, like so:
require 'plainflow/analytics'
Analytics = Plainflow::Analytics.new({
secret_key: 'YOUR_SECRET_KEY',
on_error: Proc.new { |status, msg| print msg }
})
That will create an instance of Analytics
that you can use to send data to Plainflow.
If you’re using Rails, you can stick that initialization logic in config/initializers/analytics_ruby.rb
and omit the require
call.
Note: Our ruby gem makes requests asynchronously, which can sometimes be suboptimal and difficult to debug if you’re pairing it with a queuing system like Sidekiq/delayed job/sucker punch/resqueue.
Identify
The identify
method is how you associate your users and their actions to a recognizable userId
and traits
. You can find details on the identify method payload in the Identify Documentation.
The identify
call has the following fields:
Field | Type | Description |
---|---|---|
user_id | String | ID for this user in your database |
anonymous_id , optional | String | The ID associated with the user when you don’t know who they are (either user_id or anonymous_id must be given) |
integrations , optional | Hash | A Hash specifying which destinations this should be sent to. |
traits optional | Hash | A Hash of traits you know about the user. Things like: email , name or friends . |
timestamp optional | Time | A 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 optional | Hash | A Hash that can include things like user_agent or ip . |
Example identify
:
Analytics.identify(
user_id: 'u75ed7odf3',
traits: { email: "#{ user.email }", friends: 42 },
context: {ip: '8.8.4.4'})
This example call will identify your user by their unique User ID (the one you know him by in your database) and label them with email
and friends
traits.
Track
The track
method lets you record any actions your users perform. You can find details on the track method payload.
The track
call has the following fields:
user_id | String | The ID for this user in your database. |
---|---|---|
event | String | The name of the event you’re tracking. We recommend human-readable names like Song Played or Status Updated. |
properties optional | Hash | A Hash of properties for the event. If the event was Product Added to their cart, it might have properties like price or product . |
timestamp optional | DateTime | A DateTime representing when the event took place. If the track 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 optional | Hash | A Hash that can include things like user_agent or ip . |
anonymous_id optional | String | The ID associated with the user when you don’t know who they are (either user_id or anonymous_id must be given). |
integrations optional | Hash | A Hash specifying which destinations this should be sent to. |
You’ll want to track events that are indicators of success for your site, like Signed Up, Item Purchased or Article Bookmarked.
To get started, we recommend tracking just a few important events. You can always add more later!
Example track
call:
Analytics.track(
user_id: 'u75ed7odf3',
event: 'Item Purchased',
properties: { revenue: 42.24, shipping: '48h' })
This example track
call tells us that your user just triggered the Item Purchased event with a revenue of $42.24 and chose your hypothetical ‘48h’ shipping.
track
event properties can be anything you want to record, for example:
Analytics.track(
user_id: 'f4ca124298',
event: 'Article Bookmarked',
properties: {
title: 'The Gilded Age',
author: 'Mark Twain'
})
Page
Thepage
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!
Thepage
call has the following fields:
user_id | String | The ID for this user in your database. |
---|---|---|
category optional | String | The 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 optional | String | The name of the of the page, for example Signup or Home. |
properties optional | Hash | A 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 optional | String | If you want to track users anonymously, you can include the Anonymous ID instead of a User ID |
context optional | Hash | An 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 |
Example page
call:
Analytics.page(
user_id: user_id,
category: 'Docs',
name: 'Ruby library',
properties: { url: 'https://www.plainflow.com/docs/' })
Find details on the page
payload in our Page Documentation.
Alias
alias
is how you associate one identity with another.
The alias
method definition:
Analytics.alias(previous_id: 'previous id', user_id: 'new id')
The alias
call has the following fields:
userId | String | The ID for this user in your database. |
---|---|---|
previousId | String | The previous ID to alias from. |
Here’s a full example of how we might use the alias
call:
# 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')
For more details about alias
, including the alias
call payload, check out our Alias Documentation.
Historical Import
You can import historical data by adding the timestamp
argument to any of your method calls. This can be helpful if you’ve just switched to Plainflow.
Historical imports can only be done into destinations that can accept historical timestamp’ed data. Most analytics tools like Mixpanel, Amplitude, Kissmetrics, etc. can handle that type of data just fine. One common destination that does not accept historical data is Google Analytics since their API cannot accept historical data.
Note: If you’re tracking things that are happening right now, leave out the timestamp
and our servers will timestamp the requests for you.
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
There is a maximum of 500kb
per batch request and 15kb
per call.
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
Plainflow::Analytics.new({
secret_key: 'YOUR_SECRET_KEY',
on_error: Proc.new { |status, msg| print msg },
max_queue_size: 10000,
batch_size: 100,
stub: true
})
on_error optional | Proc | A handler which is called whenever errors are returned from the API. Useful for debugging and first time destinations. |
---|---|---|
max_queue_size optional | FixNum | The max number of messages to put in the queue before refusing to queue more (defaults to 10,000 ). |
batch_size optional | FixNum | The 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 optional | TrueClass|FalseClass | If true, the requests don’t hit the server and are stubbed to be successful (defaults to false ). |
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.
AppAnalytics = Plainflow::Analytics.new({
secret_key: 'ONE_SECRET_KEY'
})
AppAnalytics.flush
Calling flush will block execution until all messages are processed, so it is not recommended in normal execution of your production application.
Turbolinks
If you’re using Ruby on Rails with the Turbolinks setting enabled, and you’re adding Plainflow.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.
Multiple Clients
Different parts of your application may require different types of batching. In that case, you can initialize multiple instances of Analytics
with different settings:
AppAnalytics = Plainflow::Analytics.new({
secret_key: 'ONE_SECRET_KEY'
})
MarketingAnalytics = Plainflow::Analytics.new({
secret_key: 'ANOTHER_SECRET_KEY'
})
Troubleshooting
If you’re having trouble we have a few tips that help common problems.
No events in my debugger
- Double check that you’ve followed all the steps in the Quickstart.
- Make sure that you’re calling one of our API methods once the library is successfully installed.
Not using Plainflow yet? Get your free account here. 👈