Amplitude Ruby Library
Overview
This is a library designed to help developers more simply interact with the Amplitude analytics service. It communicates with Amplitude over their HTTP API.
Installation
Via the command-line:
gem install amplitude-rb
Via a Gemfile:
gem 'amplitude-rb', '~> x.y.z'
Configuration
Amplitude requires an API key to accompany all HTTP API requests. This can be configured through any of the following means (in lookup order):
- Passing it to an event-tracking call in the options hash via
:api_key - Through
Amplitude.configureor by settingAmplitude.config.api_key - Environment variable,
AMPLITUDE_API_KEY
Examples:
# 1. Options hash, overrides everything else
Amplitude.track(event, api_key: 'abc')
# 2. Using Amplitude.configure in an initializer
Amplitude.configure do |config|
config.api_key = 'abc'
end
# 3. Setting it as an environment variable
export AMPLITUDE_API_KEY=abc
Additional Configuration Values
time_formatter
Amplitude requires that the time key is given as milliseconds since the
Unix epoch. The default formatter assumes that a number or a Time (or date)
object is given and performs (time.to_f * 1_000).to_i.
event_prop_formatter
Amplitude allows for an optional set of user-defined key-value pairs relating to
the event being tracked. The default formatter assumes that the given event
properties responds to to_h and uses that result.
user_prop_formatter
Amplitude allows for an optional set of user-defined key-value pairs relating to
the user being tracked. The default formatter assumes that the given user
properties responds to to_h and uses that result.
job_queue
If ActiveJob is available then this value will be the name of the queue that
the job should run in. Defaults to :default.
iid_generator
It is good practice to include the insert_id key when tracking events. This
should be a proc or lambda (or anything that responds to call) that returns
a unique identifier that can be used for the insert_id field. By default this
will use securerandom to generate a random UUID. If you do not wish to use
insert_id except when explicitly included in the event hash, set this value to
nil.
Usage
Simply ensure an API key is set (or passed as an option) before calling any event-tracking functions. Then pass a hash, or Amplitude event object, to the tracking function.
Amplitude.config.api_key = 'abc'
Amplitude.track(event_hash)
# or
Amplitude.track(event_hash, api_key: 'abc')
Asynchronous Worker
If ActiveJob is available, a job workerwill be included and the
Amplitude.queue function will be usable. It takes the exact same parameters as
Amplitude.track.
Note: while Amplitude.track returns a result object that you may inspect
for errors, Amplitude.queue will raise an error if the tracking call fails.
This is because many background queues will add jobs to a retry queue if an
uncaught error bubbles up, plus there's no good way to inspect the result of a
tracking call when it is performed asynchronously.