Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

Example usage of the Ruby SDK

A brief code example of how to use the Optimizely Feature Experimentation Ruby SDK to evaluate feature flags, activate A/B tests, or feature tests.

Once you have installed the Ruby SDK, import the Optimizely Feature Experimentation library into your code, get your Optimizely Feature Experimentation project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.

This example demonstrates the basic usage of each of these concepts:

  1. Evaluate a flag with the key product_sort using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely Feature Experimentation to record that the current user has been exposed to the experiment.

  2. Conditionally execute your feature code. You have a couple of options:

    • Based on flag enabled state, check a configuration variable on the flag called sort_method. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method they should see.
    • Based on the flag variation, run 'control' or 'treatment' code.
  3. Use event tracking to track an event called purchased. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely Feature Experimentation using the customizable event dispatcher so Optimizely can count it in your results page.

# frozen_string_literal: true

require 'optimizely/optimizely_factory'

# Initialize an Optimizely client
optimizely_client = Optimizely::OptimizelyFactory.default_instance('your_sdk_key')

# create a user and decide a flag rule (such as an A/B test) for them
user = optimizely_client.create_user_context('user123')

decision = user.decide('product_sort')

variation_key = decision.variation_key
if variation_key.nil?
  puts "[decide] error: #{decision.reasons}"

# execute code based on flag variable
enabled = decision.enabled

if enabled
  # get flag variable values

# or execute based on variation
if variation_key == 'control'
  # Execute code for variation A
elsif variation_key == 'treatment'
  # Execute code for variation B