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.
After installing the Ruby SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
-
Evaluate a flag with the key
product_sortusing thedecidemethod. This also sends a decision event to Optimizely to record that the user was exposed to the experiment. -
Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (
sort_method) to determine which experience the user gets. - Check the flag variation directly and run the corresponding control or treatment code.
- Check the flag's enabled state and read a configuration variable (
-
Track a conversion event called
purchasedto measure the experiment's impact. Thetrack_eventmethod ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment 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}"
exit(1)
end
# execute code based on flag variable
enabled = decision.enabled
if enabled
# get flag variable values
decision.variables['sort_method']
end
# or execute based on variation
if variation_key == 'control'
# Execute code for variation A
elsif variation_key == 'treatment'
# Execute code for variation B
end
user.track_event('purchased')Updated 10 days ago
