Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunityDoc feedbackLog In
GitHubNuGetDev CommunityDoc feedback

Initialize the Ruby SDK

This topic describes how to initialize the Optimizely Feature Experimentation Ruby SDK in your application.

Use the new method to initialize the Ruby SDK and instantiate an instance of the Optimizely client class that exposes API methods like Decide methods. Each client corresponds to the datafile representing the state of a project for a certain environment.## Version

SDK v3.3.2 and higher


The SDK provides a default implementation, but you may want to override the optional parameters for your production environments. For example, you can set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.


The table below lists the required and optional parameters for the new method:

stringThe JSON string representing the project.
EventDispatcherAn event handler to manage network calls.
LoggerA logger implementation to log issues.
ErrorHandlerAn error handler object to handle errors.
UserProfileServiceA user profile service.
booleanSpecifies whether the JSON should be validated. Set to true to skip JSON validation on the schema, or false to perform validation.
string(Server-side only) An access token for Optimizely Feature Experimentation SDKs (in combination with an SDK key) to fetch the datafile from an authenticated endpoint. Find your datafile access token in the Optimizely app at Settings>Environments. Select your secure environment, and copy the Datafile access token.
ArrayArrary of OptimizelyDecideOption enums. Constructing the Optimizely client with this parameter sets default decide options that apply to all Decide calls made during the lifetime of the Optimizely client. Passing options to individual Decide methods overrides these defaults.

For details on decide options, see OptimizelyDecideOption.


Instantiates an instance of the Optimizely Feature Experimentation class.


Optimizely Feature Experimentation provides out-of-the-box functionality to dynamically manage datafiles (configuration files) on either the client or the server. The Ruby SDK provides default implementations of an ProjectConfigManager. The package also includes a factory class, OptimizelyFactory, which you can use to instantiate the Optimizely Feature Experimentation SDK with the default configuration of HttpProjectConfigManager.

Whenever the experiment configuration changes, the SDK uses automatic datafile management (ADM) to handle the change for you. You can provide either a sdk_key,datafile, or both.

  • Initializing with the SDK key only polls for datafile changes in the background at regular intervals.
  • Initializing wit the datafile only does not poll for datafile changes in the background.
  • Initializing with the SDK key and datafile uses the given datafile to poll for changes in the background.

Instantiate using SDK Key (recommended)

In the Ruby SDK, you only need to pass the SDK key value to instantiate a client. Whenever the experiment configuration changes, the SDK handles the change for you.

IInclude sdk_key as a string property in the options object you pass to the default_instance method.
When you provide the sdk_key, the SDK instance downloads the datafile associated with that sdk_key. When the download completes, the SDK instance updates itself to use the downloaded datafile.

Basic example

The following code example shows basic Ruby ADM usage.

require 'optimizely'
require 'optimizely/optimizely_factory'

# Initialize an Optimizely client
optimizely_instance = Optimizely::OptimizelyFactory.default_instance('put_your_sdk_key_here')

Advanced examples

Here is a code example showing advanced configuration for Ruby ADM. See the sections below for advanced configuration properties.
This advanced example shows how to construct the individual components directly to override various configurations. This gives you full control over using implementations.

require 'optimizely'
require 'optimizely/optimizely_factory'
require 'optimizely/config_manager/http_project_config_manager'

sdk_key = '<YOUR_SDK_KEY>'
http_project_config_manager =
  sdk_key: sdk_key,
  polling_interval: 10
optimizely_instance = Optimizely::OptimizelyFactory.default_instance_with_config_manager(http_project_config_manager)
# Starting in 3.2+ there are convienence factory methods for instantiating clients
require 'optimizely/optimizely_factory'

# Instantiate with just the SDK key. The SDK will pull the datafile remotely.
sdk_key = 'AWDj34sdlfklsdfks'
optimizely_client = Optimizely::OptimizelyFactory.default_instance(sdk_key)

# You can optionally instantiate with a hard-coded datafile as well 
datafile = '{ revision: "42" }'
optimizely_client = Optimizely::OptimizelyFactory.default_instance(sdk_key, datafile)

Required SDK key with other optional arguments

require 'optimizely'
optimizely_instance = Optimizely::OptimizelyFactory.custom_instance(

Instantiate using datafile

You can also instantiate with a hard-coded datafile. If you do not pass in an SDK key, the Optimizely Client does not automatically sync newer versions of the datafile. Any time you retrieve an updated datafile, just re-instantiate the same client.
To instantiate a client for simple applications, provide a datafile specifying the project configuration for a given environment. For most advanced implementations, you should customize the logger or error handler for your specific requirements.

# Instantiate with both SDK key and datafile. The SDK will use the hard-coded datafile and will start polling for new datafiles remotely.
datafile = '{ revision: "42" }'
optimizely_client = Optimizely::OptimizelyFactory.default_instance(sdk_key, datafile)

# You can also customize the various components of the SDK (i.e. logger, error handler)
optimizely_client = Optimizely::OptimizelyFactory.custom_instance(
  # event_dispatcher
  # logger

# Prior to 3.2 you can instantiate with just a JSON datafile string
optimizely_client =

Initialize in a Rails application

To use the SDK in a Rails application, you can configure the SDK using the snippet below:

# initialize a client
Rails.configuration.optimizely_client = Optimizely::OptimizelyFactory.default_instance('SDK_KEY_HERE')

# you can access the client in your Rails controllers from the application config

The SDK spawns multiple threads when initialized. These threads have infinite loops for fetching the datafile, as well as batching and dispatching events in the background. When using in a web server that spawn multiple child processes, you need to initialize the SDK after those child processes or workers have been spawned:


after_fork do |server, worker|
   Rails.configuration.optimizely_client = Optimizely::OptimizelyFactory.default_instance('SDK_KEY_HERE')


on_worker_boot do
   Rails.configuration.optimizely_client = Optimizely::OptimizelyFactory.default_instance('SDK_KEY_HERE')


PhusionPassenger.on_event(:starting_worker_process) do |forked|
 if forked
   Rails.configuration.optimizely_client = Optimizely::OptimizelyFactory.default_instance('SDK_KEY_HERE')


HttpProjectConfigManager is an implementation of ProjectConfigManager interface which polls for the datafile and updates DatafileProjectConfig based on an update interval. To maintain the asynchronous nature of requests, it uses an AsyncScheduler which makes an HTTP GET request to the configured URL to asynchronously download the project datafile and initialize an instance of the DatafileProjectConfig.

By default, HttpProjectConfigManager blocks until the first successful datafile retrieval, up to a configurable blocking timeout. Set the frequency of the polling method and the blocking timeout when initializing the config manager.

http_project_config_manager =
  datafile: datafile
  sdk_key: sdk_key,
  polling_interval: 10,
  blocking_timeout: 15

SDK key

The SDK key composes the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval specifies a fixed delay between consecutive HTTP requests for the datafile.

Initial datafile

You can provide an initial datafile while initializing the Config Manager to bootstrap the ProjectConfigManager so that it can be used immediately without blocking execution. The initial datafile also serves as a fallback datafile if HTTP connection cannot be established. This is useful in mobile environments, where internet connectivity is not guaranteed.

The SDK discards the initial datafile after the first successful datafile poll.

Advanced configurations

You can use the following properties to customize the HttpProjectConfigManager configuration.

PropertyDefault valueDescription
datafilenullInitial datafile, typically sourced from a local cached source.
urlnullURL override location used to specify custom HTTP source for the datafile.
url_templatenullParameterized datafile URL by SDK key.
polling_interval5 minutesFixed delay between fetches for the datafile. Valid duration is between 1 and 2592000 seconds. Otherwise, default is used.
blocking_timeout15 secondsThe blocking timeout period is used to specify a maximum time to wait for initial bootstrapping. Valid blocking timeout period is between 1 and 2592000 seconds. Otherwise, default is used.
sdk_keynullOptimizely Feature Experimentation project SDK key; required unless source URL is overridden.
auto_updatetrueBoolean flag to specify if callback for datafile polling needs to execute infinitely or only once.
start_by_defaulttrueBoolean flag to specify if datafile polling should start right away, as soon as the HTTPConfigManager is initialized.

Update config notifications

The SDK triggers a notification signal when fetching a new datafile or updating a corresponding project. To subscribe to these notifications, use the method notification_center.add_notification_listener().

notification_center.add_notification_listener(Optimizely::NotificationCenter::NOTIFICATION_TYPES[:OPTIMIZELY_CONFIG_UPDATE], @callback


OptimizelyFactory provides basic utility to instantiate the Optimizely Feature Experimentation SDK with a minimal number of configuration options.

OptimizelyFactory does not capture all configuration and initialization options. For more use cases, build the resources with their constructors.

You must provide the SDK key at runtime, directly via the factory method:

optimizely_instance = Optimizely::OptimizelyFactory.default_instance(

Enable JSON schema validation

Skipping JSON schema validation enhances performance during instantiation. In the Ruby SDK, you can control whether to validate the JSON schema of the datafile when instantiating the client. This example shows how to skip JSON schema validation:

# Skip JSON schema validation (SDK versions 0.1.1 and above)
optimizely_client =, nil, nil, nil, true)

Use authenticated datafiles in secure environments

You can fetch the Optimizely datafile from an authenticated endpoint using a server-side (only) Optimizely Feature Experimentation SDK, like the Ruby SDK.

To use an authenticated datafile, download your environment's access token from the app at Settings > Environment. Select your secure environment, and copy the Datafile access token The example below shows how to initialize the Optimizely client using an access token and sdk_key, enabling the client to fetch the authenticated datafile and complete initialization.

# fetch the datafile from an authenticated endpoint
require "optimizely"

sdk_key = '<YOUR_SDK_KEY>'
datafile_access_token = '<YOUR_DATAFILE_ACCESS_TOKEN>'

config_manager =
    sdk_key: sdk_key,
    datafile_access_token: datafile_access_token

optimizely_client =
        nil ,nil, nil, nil, nil, nil,
        nil, config_manager, nil, nil

Source files

The language and platform source files containing the implementation for the Ruby SDK are available on GitHub.