Example usage of the Ruby SDK
1 min
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_sort using the decide method. 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.
- Track a conversion event called purchased to measure the experiment's impact. The track_event method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results pageExperiment 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')