Submit FeedbackJoin Developer Community

Initialize SDK

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


SDK v3.3.2+


The constructor accepts a configuration object to configure Optimizely.

Some parameters are optional because the SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want override these to 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 in Ruby.






The JSON string representing the project.



An event handler to manage network calls.



A logger implementation to log issues.



An error handler object to handle errors.



A user profile service.



Specifies whether the JSON should be validated. Set to true to skip JSON validation on the schema, or false to perform validation.



(Server-side only) Optimizely SDKs can use an access token (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.


Instantiates an instance of the Optimzely class.


Optimizely 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 Optimizely ProjectConfigManager. The package also includes a factory class, OptimizelyFactory, which you can use to instantiate the Optimizely 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. In the Ruby SDK, you can provide either sdkKey or datafile or both.

  • When initializing with just the SDK key, the SDK will poll for datafile changes in the background at regular intervals.
  • When initializing with just the datafile, the SDK will NOT poll for datafile changes in the background.
  • When initializing with both the SDK key and datafile, the SDK will use the given datafile and start polling for datafile 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.

Include sdkKey as a string property in the options object you pass to the createInstance method.

When you provide the sdkKey, the SDK instance downloads the datafile associated with that sdkKey. 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. Advanced configuration properties are described in the sections below.

This advanced example shows how to construct the individual components directly to override various configurations. This gives you full control over which implementations to use and how to use them.

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

  sdk_key = ‘123456’
  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 don't pass in an SDK key, the Optimizely Client will not automatically sync newer versions of the datafile. Any time you retrieve an updated datafile, just re-instantiate the same client.

For simple applications, all you need to provide to instantiate a client is a datafile specifying the project configuration for a given environment. For most advanced implementations, you'll want to 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 =

Initializing 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 that are used 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 will block 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 is used to compose the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval is used to specify 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 initial datafile will be discarded after the first successful datafile poll.

Advanced configurations

The following properties can be used to customize the HttpProjectConfigManager configuration.


Default value




Initial datafile, typically sourced from a local cached source.



URL override location used to specify custom HTTP source for the Optimizely datafile.



Parameterized datafile URL by SDK key.


5 minutes

Fixed delay between fetches for the datafile. Valid duration is between 1 and 2592000 seconds. Otherwise, default is used.


15 seconds

The 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.



Optimizely project SDK key; required unless source URL is overridden.



Boolean flag to specify if callback for datafile polling needs to execute infinitely or only once.



Boolean flag to specify if datafile polling should start right away, as soon as the HTTPConfigManager is initialized.

Update config notifications

A notification signal will be triggered whenever a new datafile is fetched and corresponding project config is updated. To subscribe to these notifications, use 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 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 have control over 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


Beta feature

Contact your Customer Success Manager if you are interested in becoming an early user of authenticated datafiles as part of the beta secure environment feature.

You can fetch the Optimizely datafile from an authenticated endpoint using a server-side (only) Optimizely SDK. To use an authenticated datafile, download your Optimizely environment's access token from the Optimizely app at Settings>Environments. 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/platform source files containing the implementation for Ruby are at optimizely.rb.

Did this page help you?