Skip to content
absmartlyPublic

About

A/B Smartly Ruby SDK

Resources

Code of conduct

Stars

2 stars

Watchers

2 watching

Forks

Repository files navigation

ABsmartly Ruby SDK

Ruby SDK for ABsmartly A/B testing platform.

Compatibility

The ABsmartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the best performance and code readability, Ruby 3 or later is recommended. This SDK is being constantly tested with the nightly builds of Ruby, to ensure it is compatible with the latest Ruby version.

Installation

Install the gem and add to the application's Gemfile by executing:

bundle add absmartly-sdk --version "~> 1.4"

If bundler is not being used to manage dependencies, install the gem by executing:

gem install absmartly-sdk -v 1.4.0

Getting Started

Please follow the installation instructions before trying the following code.

Initialization

This example assumes an API Key, an Application, and an Environment have been created in the ABsmartly web console.

Recommended: Named Parameters (Ruby Keyword Arguments)

The simplest and most idiomatic way to initialize the SDK in Ruby:

require 'absmartly'

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development"
)

With Optional Parameters

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development",
  timeout: 5000,      # Connection timeout in milliseconds (default: 3000)
  retries: 3          # Max retry attempts (default: 5)
)

Alternative: Global Configuration

For applications that need a single SDK instance shared globally:

require 'absmartly'

Absmartly.configure_client do |config|
  config.endpoint = "https://your-company.absmartly.io/v1"
  config.api_key = "YOUR-API-KEY"
  config.application = "website"
  config.environment = "development"
end

Alternative: Full Configuration

For use cases where you need custom providers, serializers, or other low-level configurations:

require 'absmartly'

client_config = ClientConfig.create
client_config.endpoint = "https://your-company.absmartly.io/v1"
client_config.api_key = "YOUR-API-KEY"
client_config.application = "website"
client_config.environment = "development"
client_config.connect_timeout = 3.0
client_config.connection_request_timeout = 3.0
client_config.retry_interval = 0.5
client_config.max_retries = 5
# Opt in to retrying HTTP statuses (none by default). Retrying a publish after
# a 5xx may duplicate events the collector already stored.
client_config.retry_statuses = [502, 503, 504]
# Opt in to retrying a refused connection on the context fetch (off by default).
# Each retry waits retry_interval, doubling each time.
client_config.retry_connection_failures = true

sdk_config = ABSmartlyConfig.create
sdk_config.client = Client.create(client_config)

sdk = ABSmartly.create(sdk_config)

SDK Options

Parameter Type Required? Default Description
endpoint String ✅ nil The URL to your API endpoint. Most commonly "https://your-company.absmartly.io/v1" (first positional parameter)
api_key String ✅ nil Your API key which can be found on the Web Console.
application String ✅ nil The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running.
environment String ✅ nil The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure.
timeout Integer ❌ 3000 The connection and request timeout in milliseconds. Converted to seconds internally.
retries Integer ❌ 5 The maximum number of retries before giving up.
context_event_logger ContextEventLogger ❌ nil A ContextEventLogger instance implementing handle_event(event, data) to receive SDK events. See "Custom Event Logger" below.

Creating a New Context

Basic Context Creation

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development"
)

context_config = ContextConfig.create
context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')

context = sdk.create_context(context_config)

Or using the global configuration approach:

Absmartly.configure_client do |config|
  config.endpoint = "https://your-company.absmartly.io/v1"
  config.api_key = "YOUR-API-KEY"
  config.application = "website"
  config.environment = "development"
end

context_config = Absmartly.create_context_config
context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')

context = Absmartly.create_context(context_config)

Async Context Creation

When you want to avoid blocking the current thread while fetching experiment data, use create_context_async. It returns a Context immediately and fetches data in a background thread.

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development"
)

context_config = ContextConfig.create
context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')

context = sdk.create_context_async(context_config)

# Do other work while data is being fetched...

# Block until the context is ready (or use a timeout)
context.wait_until_ready
# context.wait_until_ready(5) # with a 5-second timeout

if context.ready?
  treatment = context.treatment('exp_test_experiment')
end

A refresh that was already in flight when the initial fetch failed, and then installs data, recovers the context (a failed refresh installs nothing, and a refresh called after the context failed is a no-op, as in 1.3.0): it installs the data, clears failed? and ready_error, and events still queued are published with the next publish. Exposures made while the context was failed are unassigned (assigned: false, experiment id 0; control unless an override forces a variant), which the collector excludes from analysis; a publish made while the context was failed still drops its events, as in 1.3.0. A refresh that succeeds before the background fetch lands makes the context ready with the refreshed data; that data is kept when the initial fetch completes later, and the "ready" event is logged once the initial fetch completes.

Read methods (treatment, peek_treatment, variable_value, peek_variable_value, variable_keys, experiments, custom_field_keys, custom_field_value) raise IllegalStateException ("ABSmartly Context is not yet ready") until the context is ready, and ("ABSmartly Context is closed") after close or finalize (except experiments, which still works after finalize). Check ready? first. A context whose data fetch failed is ready and failed: reads return control (0) and the caller's defaults.

Or using the global configuration approach:

context = Absmartly.create_context_async(context_config)
context.wait_until_ready

With Pre-fetched Data

When doing full-stack experimentation with ABsmartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document.

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development"
)

context_config = ContextConfig.create
context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')

server_context = sdk.create_context(context_config)

client_context_config = ContextConfig.create
client_context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')

client_context = sdk.create_context_with(client_context_config, server_context.data)

Refreshing the Context with Fresh Experiment Data

For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.

The refresh method can be called manually. The refresh method pulls updated experiment data from the ABsmartly collector and will trigger recently started experiments when treatment is called again.

context.refresh

Setting Extra Units

You can add additional units to a context by calling the set_unit or set_units methods. These methods may be used, for example, when a user logs in to your application and you want to use the new unit type in the context.

Note: You cannot override an already set unit type as that would be a change of identity and would throw an exception. In this case, you must create a new context instead. The set_unit and set_units methods can be called before the context is ready.

context_config.set_unit('session_id', 'bf06d8cb5d8137290c4abb64155584fbdb64d8')
context_config.set_unit('user_id', '123456')
context = Absmartly.create_context(context_config)

or

context_config.set_units(
  session_id: 'bf06d8cb5d8137290c4abb64155584fbdb64d8',
  user_id: '123456'
)
context = Absmartly.create_context(context_config)

Basic Usage

Selecting a Treatment

treatment = context.treatment('exp_test_experiment')

if treatment.zero?
  # user is in control group (variant 0)
else
  # user is in treatment group
end

Treatment Variables

Variables allow you to configure experiment variants dynamically:

default_button_color = 'red'
button_color = context.variable_value('button.color', default_button_color)

Shared variable keys

When several experiments define the same variable key, the SDK checks the experiments whose variants define it in experiment id order. The first one the unit is assigned to, overridden in or rule-assigned in wins, and only that experiment is exposed. If the winner's variant does not define the key, variable_value returns your default rather than reading a later experiment. If no experiment wins, a held-out unit reads the control value of the first held-out experiment; otherwise your default is returned and no experiment is exposed. peek_variable_value follows the same rule without exposing anything.

Peek at Treatment Variants

Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The ABsmartly SDK provides peek_treatment and peek_variable_value methods for that.

treatment = context.peek_treatment('exp_test_experiment')

Peeking at Variables

button_color = context.peek_variable_value('button.color', 'red')

Overriding Treatment Variants

During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the set_override and/or set_overrides methods. These methods can be called before the context is ready.

context.set_override('exp_test_experiment', 1) # force variant 1 of treatment

context.set_overrides(
  'exp_test_experiment' => 1,
  'exp_another_experiment' => 0
)

Advanced

Context Attributes

Attributes are used to pass meta-data about the user and/or the request. They can be used later in the Web Console to create segments or audiences. They can be set using the set_attribute or set_attributes methods, before or after the context is ready.

context.set_attribute('user_agent', request.user_agent)

context.set_attributes(
  customer_age: 'new_customer',
  account_type: 'premium'
)

The application and environment configured on the client are available to audience filters and assignment rule conditions as application and environment. A name that is unset or empty is left out, so a filter on it sees no value. An attribute you set with the same name takes precedence. They are not added to published attributes, since the collector attaches them itself.

Assignment Rules

Experiments can define assignment rules on the Web Console. They are evaluated in order and the first matching rule decides the variant, taking precedence over audience targeting, traffic allocation and custom assignments; only set_override beats a rule. Rule-assigned exposures are flagged ruleOverride so they are excluded from analysis.

  • An assign rule gives a fixed variant.
  • A split rule randomizes the unit over its own percentages, e.g. 20/30/50. While the experiment's unit is missing, it gives the full-on variant (0 for an experiment that is not full-on); once the unit is set, the rule is re-resolved unless that variant was already exposed.

Rule conditions are audience expressions, so they can use your attributes, application, environment and the semver_eq, semver_gt, semver_gte, semver_lt and semver_lte operators, e.g. {"semver_gte": [{"var": "app_version"}, {"value": "2.4.0"}]}.

Holdouts

Experiments can be covered by holdouts set up on the Web Console. A holdout keeps a share of units out of every experiment it covers, so you can measure the combined effect of those experiments. The SDK handles this for you: no code changes are needed.

  • A held-out unit gets control (variant 0; for a shared variable key its control value is used only when no other experiment defining the key wins, see Shared variable keys) for each covered experiment, and no exposure is queued for that experiment.
  • The holdout queues its own exposure, once per unit type, the first time the unit sees a covered experiment, whether it is held out or not. Like every exposure, it reaches the collector on publish or close.
  • A unit held out by any of the holdouts covering an experiment is held out of it.
  • A holdout with three arms holds full-on experiments out only in its first arm, and other experiments in its first two arms.
  • set_override and a matching assignment rule still win over a holdout; the holdout's exposure is still queued.
  • Peeking (peek_treatment, peek_variable_value) never queues exposures.
  • Set the unit before reading a covered experiment. An experiment read with treatment or variable_value before its unit type is set gets no holdout arm; set_unit alone does not change that exposed assignment or expose the holdout for it. A later refresh that changes the experiment or its coverage can rebuild the assignment. The exception is an overridden experiment, as in the Java SDK: its holdout is exposed by the next variable_value read after set_unit (not by treatment); the override still wins.

Custom Assignments

Sometimes it may be necessary to override the automatic selection of a variant. For example, if you wish to have your variant chosen based on data from an API call. This can be accomplished using the set_custom_assignment method.

chosen_variant = 1
context.set_custom_assignment('experiment_name', chosen_variant)

If you are running multiple experiments and need to choose different custom assignments for each one, you can do so using the set_custom_assignments method.

assignments = {
  'experiment_name' => 1,
  'another_experiment_name' => 0,
  'a_third_experiment_name' => 2
}

context.set_custom_assignments(assignments)

Tracking Goals

Goals are created in the ABsmartly web console.

context.track('payment', {
  item_count: 1,
  total_amount: 1999.99
})

Publishing Pending Data

Sometimes it is necessary to ensure all events have been published to the ABsmartly collector, before proceeding. You can explicitly call the publish method.

context.publish

Finalizing

The close method will ensure all events have been published to the ABsmartly collector, like publish, and will also "seal" the context, throwing an error if any method that could generate an event is called.

If the collector rejects the final publish, close logs an "error" event, drops that batch and still seals the context, as in v1.3.0. Events tracked while that request was in flight are not part of the rejected batch, so close sends them before sealing.

context.close

finalize works like the other ABsmartly SDKs: if the final publish fails it raises the failure (a StandardError, so an ordinary rescue catches it), the context stays open and the events stay queued, so finalize can be called again to retry. It logs the "finalize" event instead of "close", and experiments, set_override and set_overrides keep working after it.

begin
  context.finalize
rescue StandardError => e
  # retry later: the events are still queued
end

Both sealing methods allow one extra publish for events queued during the first request. If events are still queued after that extra publish (whether it succeeded, or close dropped its rejected batch), they stay queued, the context stays open, and the method raises StandardError ("Events queued while closing; retry close or finalize"); those events are not sent in the same call, so retry after the producer stops. Otherwise a rejection follows the rules above: close logs the error, drops that batch and seals (as in v1.3.0), and finalize raises the rejection and stays open.

Custom Event Logger

The ABsmartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context in the context config.

class CustomEventLogger < ContextEventLogger
  def handle_event(event, data)
    case event
    when EVENT_TYPE::EXPOSURE
      puts "Exposed to experiment: #{data.name}"
    when EVENT_TYPE::GOAL
      puts "Goal tracked: #{data.name}"
    when EVENT_TYPE::ERROR
      puts "Error: #{data}"
    when EVENT_TYPE::PUBLISH
      puts "Events published: #{data.length} events"
    when EVENT_TYPE::READY
      puts "Context ready with #{data.experiments.length} experiments"
    when EVENT_TYPE::REFRESH
      puts "Context refreshed with #{data.experiments.length} experiments"
    when EVENT_TYPE::CLOSE, EVENT_TYPE::FINALIZE
      puts "Context closed"
    end
  end
end

sdk = ABSmartly.new(
  "https://your-company.absmartly.io/v1",
  api_key: "YOUR-API-KEY",
  application: "website",
  environment: "development",
  context_event_logger: CustomEventLogger.new
)

Or using the global configuration approach:

Absmartly.configure_client do |config|
  config.endpoint = "https://your-company.absmartly.io/v1"
  config.api_key = "YOUR-API-KEY"
  config.application = "website"
  config.environment = "development"
  config.event_logger = CustomEventLogger.new
end

The data parameter depends on the type of event. Currently, the SDK logs the following events:

Event Types

Event When Data
Error Context receives an error Error object thrown
Ready Context turns ready ContextData used to initialize the context
Refresh Context.refresh() method succeeds ContextData used to refresh the context
Publish Context.publish() method succeeds PublishEvent sent to the collector
Exposure Context.treatment() method succeeds on first exposure Exposure data enqueued for publishing
Goal Context.track() method succeeds GoalAchievement enqueued for publishing
Close Context.close() method succeeds the first time nil
Finalize Context.finalize() method succeeds the first time nil

Platform-Specific Examples

Using with Ruby on Rails

# config/initializers/absmartly.rb
require 'absmartly'

Absmartly.configure_client do |config|
  config.endpoint = ENV['ABSMARTLY_ENDPOINT']
  config.api_key = ENV['ABSMARTLY_API_KEY']
  config.application = "website"
  config.environment = Rails.env
end

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :setup_absmartly_context
  after_action :close_absmartly_context

  private

  def setup_absmartly_context
    context_config = Absmartly.create_context_config
    context_config.set_unit('session_id', session.id.to_s)
    context_config.set_unit('user_id', current_user&.id&.to_s) if current_user

    @absmartly_context = Absmartly.create_context(context_config)
  rescue => e
    Rails.logger.error "ABsmartly context creation failed: #{e.message}"
    @absmartly_context = nil
  end

  def close_absmartly_context
    @absmartly_context&.close
  end
end

# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    treatment = @absmartly_context&.treatment('exp_product_layout') || 0

    if treatment == 0
      render 'show_control'
    else
      render 'show_treatment'
    end
  end
end

Using with Sinatra

require 'sinatra'
require 'absmartly'

configure do
  Absmartly.configure_client do |config|
    config.endpoint = ENV['ABSMARTLY_ENDPOINT']
    config.api_key = ENV['ABSMARTLY_API_KEY']
    config.application = "website"
    config.environment = ENV['RACK_ENV']
  end
end

use Rack::Session::Cookie, secret: ENV['SESSION_SECRET']

before do
  context_config = Absmartly.create_context_config
  context_config.set_unit('session_id', session[:session_id] ||= SecureRandom.uuid)

  @absmartly_context = Absmartly.create_context(context_config)
end

after do
  @absmartly_context&.close
end

get '/' do
  treatment = @absmartly_context.treatment('exp_test_experiment')

  if treatment == 0
    erb :control
  else
    erb :treatment
  end
end

Using with Rack Middleware

# config.ru
require 'absmartly'

class ABsmartlyMiddleware
  def initialize(app)
    @app = app

    Absmartly.configure_client do |config|
      config.endpoint = ENV['ABSMARTLY_ENDPOINT']
      config.api_key = ENV['ABSMARTLY_API_KEY']
      config.application = "website"
      config.environment = ENV['RACK_ENV']
    end
  end

  def call(env)
    request = Rack::Request.new(env)

    context_config = Absmartly.create_context_config
    context_config.set_unit('session_id', request.session['session_id'])

    context = Absmartly.create_context(context_config)

    env['absmartly.context'] = context

    begin
      @app.call(env)
    ensure
      context.close
    end
  end
end

use ABsmartlyMiddleware
run MyApp

About A/B Smartly

A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.

Have a look at our growing list of clients and SDKs:

About

A/B Smartly Ruby SDK

Resources

Code of conduct

Stars

2 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages