Skip to main content

Ruby SDK

Introduction

Welcome to the developer documentation for the Kameleoon Ruby SDK! Our SDK gives you the possibility of running experiments and activating feature flags on your back-end Ruby server. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.

You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial which we have prepared to walk you through the installation and implementation.

Latest version of the Ruby SDK: 2.1.0 (changelog).

Getting started

This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Ruby applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.

Creating an experiment

First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that server-side type is chosen as shown below:

Server-side experiment

Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the trigger_experiment() method.

Installing the SDK

Installing the Ruby client

gem install kameleoon-client-ruby

Installing the SDK can be directly achieved through an Ruby gem package. Our package is hosted on the official RubyGems repository, so you just have to run the following command:

gem install kameleoon-client-ruby

Additional configuration

You should provide credentials for the Ruby SDK via a configuration file, which can also be used to customize the SDK behavior. A sample configuration file can be obtained here. We suggest to install this file to the default path of /etc/kameleoon/client-ruby.yaml, but you can also put it in another location and passing the path as an argument to the Kameleoon::ClientFactory.Create() method. With the current version of the Ruby SDK, those are the available keys:

  • client_id: a client_id is required for authentication to the Kameleoon service.
  • client_secret: a client_secret is required for authentication to the Kameleoon service.
  • actions_configuration_refresh_interval: this specifies the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and feature flags are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the default interval is 60 minutes.
  • visitor_data_maximum_size: this specifies the maximum amount of memory that the hash holding all the visitor data (in particular custom data) can take (in MB). If not specified, the default size is 500MB.
  • environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information
note

To learn more about client_id and client_secret, as well as how to obtain them, refer to the API credentials article. Note that the Kameleoon Ruby SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.

Initializing the Kameleoon client

require "kameleoon"

site_code = "a8st4f59bj"

kameleoon_client = Kameleoon::ClientFactory.create(site_code)

kameleoon_client = Kameleoon::ClientFactory.create(site_code, false, "/etc/kameleoon/client-ruby.yaml")

# Second version of the Kameleoon::Client, using an asynchronous trigger_experiment() method
kameleoon_client = Kameleoon::ClientFactory.create(site_code, true)

After installing the SDK into your application, configuring the correct credentials (in /etc/kameleoon/client-ruby.yaml) and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client in your application code.

The code on the right gives a clear example. A Kameleoon::Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.

note

It's the developers' responsability to ensure proper logic of their application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. This is actually easy to do, because this corresponds to the implementation of the default / reference variation logic, which should be done in any case. The code samples on the next paragraph show examples of such an approach.

require_relative "boot"
require "rails/all"
require "kameleoon"
Bundler.require(*Rails.groups)

module App
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
if defined?(Rails::Server)
config.after_initialize do
site_code = "a8st4f59bj"
config.kameleoon_client = Kameleoon::ClientFactory.create(site_code)
end
end
end
end

If you use Ruby on Rails, we recommend you to initialize the Kameleoon client at server start-up, in the application.rb file.

class YourController < ApplicationController
def index
kameleoon_client = App::Application.config.kameleoon_client
# Your controller code, using the kameleoon_client
end
end

You can then access the Kameleoon client in your controllers:

Triggering an experiment

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com") # Cookies hash of Ruby on Rails. If you are not using Rails, it should be like that: { 'kameleoonVisitorCode' => 'cookie_value' }

begin
variation_id = kameleoon_client.trigger_experiment(visitor_code, 75253)
rescue Kameleoon::Exception::NotTargeted
# The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variation_id = 0
rescue Kameleoon::Exception::NotAllocated
# The user triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic
variation_id = 0
rescue Kameleoon::Exception::ExperimentConfigurationNotFound
# The user will not be counted into the experiment, but should see the reference variation
variation_id = 0
end

if variation_id == 0
# This is the default / reference number of products to display
recommended_products_number = 5
elsif variation_id == 148382
# We are changing number of recommended products for this variation to 10
recommended_products_number = 10
elsif variation_id == 187791
# We are changing number of recommended products for this variation to 8
recommended_products_number = 8
end

# Here you should have code to generate the HTML page back to the client, where recommendedProductsNumber will be used

Running an A/B experiment on your Ruby application means bucketing your visitors into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.

Triggering an experiment by calling the trigger_experiment() method will register a random variation for a given visitor_code. If this visitor_code is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation assigned for the given experiment.

note

Obtaining a Kameleoon visitor_code for the current HTTP request is an important step of the process. You should use the provided get_visitor_code helper method for this (details available on the reference documentation).

note

The trigger_experiment() method will quite often throw out exceptions. You should generally treat an exception as if the user was bucketed into the reference. Some possible common exceptions:

  • When the experiment has not yet been launched on the Kameleoon platform (but the code implementing the experiment on the Ruby application's side is already deployed), this results in a Kameleoon::Exception::ExperimentConfigurationNotFound exception.
  • If you used targeting on your experiment, the Kameleoon::Exception::NotTargeted exception will be thrown to indicate that the current visitor is not targeted.
note

The trigger_experiment() method will make a call to our servers for tracking purposes, but the association of a variation with the visitorCode for this experiment (this operation is also called the bucketing of the visitors) will be made directly in the SDK code. Thus the method will instantly return the variationID.

note

Every change of the deviation (traffic repartition between variations) for the experiment will trigger a mandatory reallocation.
This will happen even if you did not select the "Reallocation" checkbox in the traffic management interface. A reallocation means that all visitors that had been previously exposed to the experiment will again be bucketed, and thus can be assigned to a new, different variation.

Depending on your particular experiment, this can have some impact on the user experience and on the results of the test. We do NOT recommend changing the deviation for server side experiments at all if possible.
Read more about reallocation in this article.

Implementing variation code

if variation_id == 0
# This is the default / reference number of products to display
recommended_products_number = 5
elsif variation_id == 148382
# We are changing number of recommended products for this variation to 10
recommended_products_number = 10
elsif variation_id == 187791
# We are changing number of recommended products for this variation to 8
recommended_products_number = 8
end
# Here you should have code to generate the response back to the client, where recommended_products_number will be used.

To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs (as well as the experiment ID) by opening the experiment in the back-office interface. By convention, the reference (original variation) always has an ID equal to 0.

Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variation_id for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.

Get variationID

Tracking conversion

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
goal_id = 83023

kameleoon_client.track_conversion(visitor_code, goal_id);

After you are done triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.

For this purpose, use the track_conversion() method of the SDK as shown in the example. You need to pass the visitor_code and goal_id parameters so we can correctly track conversions for this particular visitor.

Get goalID

Obtaining results

Once your implementation is in place on the server side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly the same way.

After the experiment is launched, the first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via trigger_experiment(), track_conversion() or flush() methods).

Technical considerations

Kameleoon made an important architectural design decision with its SDK technology, namely that every SDK must comply with a zero latency policy. In practice, this means that any blocking remote server call is banned, as even the fastest remote call would add a 20ms latency to your application. And if for any reason our servers are slower to reply than usual (unfortunately, this can happen), this delay can quickly increase to hundreds of milliseconds, seconds... or even completely block the load of the web page for the end user. We believe that web performance is of paramount importance in today's world and we don't think adding server-side A/B testing or feature flagging capabilities should come at the cost of an increased web page rendering time. For this reason, we guarantee that the use of our SDKs has absolutely no impact on the performance of the host platform.

However, having a zero latency policy does impose some constraints. The main one is that user data about your visitor should be kept locally, and not fetched from a remote server. For instance, if you set a custom data for a given visitor, we must store this somehow in your server / infrastructure, not on our (remote) side.

In the case of the Ruby SDK, this is implemented via a hash of visitor data (where keys are the visitor_codes) directly on RAM. So if you use Kameleoon::CustomData.new() and then kameleoon_client.add_data() methods, the information will be stored in the application's RAM (the one hosting the SDK, usually an application server). The map is regularly cleaned (old visitors data is erased) so it should usually not grow too big in size, unless you have a very big traffic and use lots of custom data.

note

To be able to control how much maximum RAM the SDK can use with this hash, you can use the visitor_data_maximum_size configuration parameter. The default value is 500MB, meaning the additional RAM overhead of the SDK will not be more than 500MB on your host server (if you use Custom Data, if you don't it will be much lower).

caution

Since the visitor data is kept in RAM, it is obviously lost if you restart your application server. This is usually not an issue, as important custom data is usually fetched from persistent database and then tagged on the current visitor. A reboot should thus only affect the Kameleoon custom data of the sessions active when the reboot occured.

Overview

When you update your experiment or feature flag configuration, the SDK can get it in two different ways. The first - polling - consists in retrieving the configuration at regular intervals. The second - streaming - is to retrieve the new configuration immediately.

Polling

This mode of obtaining the configuration is used by default. The SDK will send a request to Cloudflare CDN at regular intervals to retrieve the configuration. If you have not set an interval in the SDK configuration, the configuration in SDK will be refreshed every 60 minutes. It can be configured with actions_configuration_refresh_interval parameter.

    Benefits:
  • When intervals are moderately spaced, this way of updating configuration consumes nominal memory and network resources.

Streaming

This mode allows the SDK to automatically take into account the new configuration without delay. When turned on, Kameleoon SDK is notified of any changes to the configuration in real-time, thanks to server-sent events (SSE).

    Benefits:
  • Makes it possible to propagate and apply a new configuration in real-time.
  • Reduce network traffic compared to polling at short intervals, as streaming does not require sending periodic requests. It opens the connection once and then keeps it permanently open and ready to receive data.

If you rely on instant data updates (real-time), then streaming is for you. If you wish to activate this mode, please contact us.

Reference

This is a full reference documentation of the Ruby SDK.

If this is your first time working with the Ruby SDK, we strongly recommend you go over our Getting started tutorial to integrate the SDK and start experimenting in a few minutes.

Kameleoon::ClientFactory

create

kameleoon_client = Kameleoon::ClientFactory.create("a8st4f59bj")

kameleoon_client = Kameleoon::ClientFactory.create("a8st4f59bj", false, "/etc/kameleoon/client-ruby.yaml")

The starting point for using the SDK is the initialization step. All interactions with the SDK are done through an object named Kameleoon::Client, therefore you need to create this object.

Arguments
NameTypeDescription
site_codeStringCode of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory.
configuration_file_pathStringPath to the SDK configuration file. This field is optional and set to /etc/kameleoon/client-ruby.yaml by default.
client_idStringThis parameter is used for OAUth 2.0 authentication to our service. This field is optional, as it can be provided via the configuration file. However, it must either be supplied by the configuration file or by this method, else a Kameleoon::Exception::CredentialsNotFound exception will be thrown.
client_secretStringThis parameter is used for OAUth 2.0 authentication to our service. This field is optional, as it can be provided via the configuration file. However, it must either be supplied by the configuration file or by this method, else a Kameleoon::Exception::CredentialsNotFound exception will be thrown.

Kameleoon::Client

get_visitor_code

require "securerandom"

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com", visitor_code)

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com", SecureRandom.uuid)
note

Previously named: obtain_visitor_code - deprecated since SDK version 2.0.0 and will be removed in a future releases.

The get_visitor_code helper method should be called to obtain the Kameleoon visitor_code for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:

  1. First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.

  2. If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the default_visitor_code argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.

  3. In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.

For more information, refer to this article.

note

If you provide your own visitor_code, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of visitor_code is limited to 255 characters. Any excess characters will throw an exception.

Arguments
NameTypeDescription
cookiesHashCookies on the current HTTP request should be passed, as a Hash object ({:cookie_name => cookie_value}). If you use Rails, you can directly pass the cookies variable. This field is mandatory.
top_level_domainStringYour current top level domain for the concerned site (this information is needed to set the corresponding cookie accordingly, on the top level domain). This field is mandatory.
default_visitor_codeStringThis parameter will be used as the visitor_code if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitor_code will be generated.
Return value
TypeDescription
StringA visitor_code that will be associated with this particular user and should be used with most of the methods of the SDK.

trigger_experiment

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
experiment_id = 75253

begin
variation_id = kameleoon_client.trigger_experiment(visitor_code, experiment_id)
rescue Kameleoon::Exception::NotTargeted
# The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variation_id = 0
rescue Kameleoon::Exception::NotAllocated
# The user triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic
variation_id = 0
rescue Kameleoon::Exception::ExperimentConfigurationNotFound
# The user will not be counted into the experiment, but should see the reference variation
variation_id = 0
end

To trigger an experiment, call the trigger_experiment() method of our SDK.

This method takes visitor_code and experiment_id as mandatory arguments to register a variation for a given user.

If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitor_code is already registered with a variation, it will detect the previously registered variation and return the variation_id.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
experiment_idIntegerID of the experiment you want to expose to a user. This field is mandatory.
timeoutIntegerTimeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If not provided, it will use the default value of 2000 milliseconds.
Return value
NameTypeDescription
variation_idIntegerID of the variation that is registered for a given visitor_code. By convention, the reference (original variation) always has an ID equal to 0.
Exceptions Thrown
Error MessageDescription
Kameleoon::Exception::NotTargetedException indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder.
Kameleoon::Exception::NotAllocatedException indicating that the current visitor / user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked.
Kameleoon::Exception::ExperimentConfigurationNotFoundException indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side).

feature_active?

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

feature_key = "new_checkout"
has_new_checkout = false

begin
has_new_checkout = kameleoon_client.feature_active?(visitor_code, feature_key)
rescue Kameleoon::Exception::FeatureConfigurationNotFound
# The user will not be counted into the experiment, but should see the reference variation
has_new_checkout = false
end

if has_new_checkout
# Implement new checkout code here
end
note

Previously named: activate_feature - deprecated since SDK version 2.0.0 and will be removed in a future releases.

This method takes a visitor_code and feature_key as mandatory arguments to check if the specified feature will be active for a given user.

If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous FeatureFlag value.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
feature_keyStringKey of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
BooleanValue of the feature that is registered for a given visitor_code.
Exceptions Thrown
TypeDescription
Kameleoon::Exception::FeatureConfigurationNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

get_feature_variation_key

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

feature_key = "feature_key"
variation_key = ""

begin
variation_key = kameleoon_client.get_feature_variation_key(visitor_code, feature_key)
case variation_key
when 'on'
# main variation key is selected for visitorCode
when 'alternative_variation'
# alternative variation key
else
# default variation key
end
rescue Kameleoon::Exception::FeatureConfigurationNotFound
# The user will not be counted into the experiment, but should see the reference variation
rescue Kameleoon::Exception::VisitorCodeNotValid
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
end

To get feature variation key, call the get_feature_variation_key method of our SDK.

This method takes a visitor_code and feature_key as mandatory arguments to get variation key for a given user.

If such a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Arguments
NameTypeDescription
visitor_codestringUnique identifier of the user. This field is mandatory.
feature_keystringKey of the feature you want to expose to a user. This field is mandatory.
Return value
TypeDescription
stringVariation key of the feature flag that is registered for a given visitor_code.
Exceptions Thrown
TypeDescription
Kameleoon::Exception::FeatureConfigurationNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

get_feature_variable

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

feature_key = "feature_key"
variation_key = ""
variable_name = "variable_name"

begin
variable_value = kameleoon_client.get_feature_variable(visitor_code, feature_key, variable_name)
# your custom code depending of variable_value, e.g.
case variable_value
when 'value-1'
# your custom code if variable == 'value-1'
when 'value-2'
# your custom code if variable == 'value-2'
end
rescue Kameleoon::Exception::FeatureConfigurationNotFound
# The user will not be counted into the experiment, but should see the reference variation
rescue Kameleoon::Exception::FeatureVariableNotFound
# Requested variable not defined on Kameleoon's side
rescue Kameleoon::Exception::VisitorCodeNotValid
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
end
note

Previously named: obtain_feature_variable - deprecated since SDK version 2.1.0 and will be removed in a future releases.

To get variable of variation key associated with a user, call the get_feature_variable method of our SDK.

This method takes a visitor_code, feature_key and variable_name as mandatory arguments to get a variable of variation key for a given user.

If such a user has never been associated with this feature flag, the SDK returns a variable value of variation key randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the variable value for previous associated variation. If the user does not match any of the rules, the variable of default value will be returned.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Arguments
NameTypeDescription
visitor_codestringUnique identifier of the user. This field is mandatory.
feature_keystringKey of the feature you want to expose to a user. This field is mandatory.
variable_namestringName of the variable you want to get a value. This field is mandatory.
Return value
TypeDescription
anyValue of variable of variation that is registered for a given visitor_code for this feature flag. Possible types: boolean, number, string, hash
Exceptions Thrown
TypeDescription
Kameleoon::Exception::FeatureConfigurationNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
Kameleoon::Exception::FeatureVariableNotFoundException indicating that the requested variable has not been found. Check that the variable's key matches the one in your code.

get_variation_associated_data

require "json"

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
experiment_id = 75253

begin
variation_id = kameleoon_client.trigger_experiment(visitor_code, experiment_id)
json_object = kameleoon_client.get_variation_associated_data(variation_id) # Return a json encoded string
first_name = json_object["firstName"]
rescue Kameleoon::Exception::VariationConfigurationNotFound
# The variation is not yet activated on Kameleoon's side, ie the associated experiment is not online
end
note

Previously named: obtain_variation_associated_data - deprecated since SDK version 2.0.0 and will be removed in a future releases.

To retrieve JSON data associated with a variation, call the get_variation_associated_data method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.

This method takes the variation_id as a parameter and will return the data as a Hash instance. It will throw an exception (Kameleoon::Exception::VariationConfigurationNotFound) if the variation ID is wrong or corresponds to an experiment that is not yet online.

Arguments
NameTypeDescription
variation_idIntegerID of the variation you want to obtain associated data for. This field is mandatory.
Return value
TypeDescription
HashData associated with this variationID.
Exceptions Thrown
TypeDescription
Kameleoon::Exception::VariationConfigurationNotFoundException indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side.

get_feature_all_variables

featureKey := "test_feature_variables"
variationKey := "on"

begin
data = kameleoon_client.get_feature_all_variables(feature_key, variable_key)
rescue Kameleoon::Exception::FeatureConfigurationNotFound
# The feature is not yet activated on Kameleoon's side
rescue Kameleoon::Exception::VariationConfigurationNotFound
# Requested variation not defined on Kameleoon's side
end

To retrieve the all feature variables, call the get_feature_all_variables method of our SDK. A feature variables can be changed easily via our web application.

This method takes feature_key and variation_key as mandatory arguments. It will return the data with the object type, as defined on the web interface. Throws an error (FeatureConfigurationNotFound) if the requested feature flag has not been found in the client configuration of the SDK. If variation key isn't found the method throws (VariationConfigurationNotFound) error.

Arguments
NameTypeDescription
feature_keystringKey of the feature flag you want to obtain. This field is mandatory.
variation_keystringKey of the variation you want to obtain. This field is mandatory.
Return value
TypeDescription
HashData associated with this feature flag and variation. The values can be a String, Boolean, Number or Hash (depending on the type defined on the web interface).
Exceptions Thrown
TypeDescription
Kameleoon::Exception::FeatureConfigurationNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
Kameleoon::Exception::VariationConfigurationNotFoundException indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side.

track_conversion

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
goal_id = 83023

kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))
kameleoon_client.add_data(
visitor_code,
Kameleoon::PageView.new("https://url.com", "title", [3]),
Kameleoon::Interest.new(2)
)
kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10, false))
kameleoon_client.track_conversion(visitor_code, goal_id)

To track conversion, use the track_conversion() method. This method requires visitor_code and goal_id to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitor_code is usually identical to the one that was used when triggering the experiment.

The track_conversion() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
goal_idIntegerID of the goal. This field is mandatory.
revenueFloatRevenue of the conversion. This field is optional.

addData

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))
kameleoon_client.add_data(
visitor_code,
Kameleoon::PageView.new("https://url.com", "title", [3]),
Kameleoon::Interest.new(0)
)
kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10, false))

To associate various data with the current user, we can use the add_data() method. This method requires the visitor_code as a first parameter, and then accepts several additional parameters. These additional parameters represent the various Data Types allowed in Kameleoon.

Note that the add_data() method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the flush() method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush().

note

The trigger_experiment() and track_conversion() methods also sends out previously associated data, exactly as the flush() method.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
data_typesKameleoonDataCustom data types which may be passed separated by a comma.

flush

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")

kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))
kameleoon_client.add_data(
visitor_code,
Kameleoon::PageView.new("https://url.com", "title", [3]),
Kameleoon::Interest.new(0)
)
kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10, false))

kameleoon_client.flush(visitor_code)

Data associated with the current user via add_data() method is not immediately sent to the server. It is stored and accumulated until it is sent automatically by the trigger_experiment() or track_conversion() methods, or manually by the flush() method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the add_data() method a dozen times, it would be a waste of ressources to send data to the server after each add_data() invocation. Just call flush() once at the end.

The flush() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.

get_feature_list

feature_list = kameleoon_client.get_feature_list

Returns a list of feature flag keys currently available for the SDK

Return value
TypeDescription
ArrayList of feature flag's keys

get_active_feature_list_for_visitor

active_feature_flag_list = kameleoon_client.get_active_feature_list_for_visitor(visitor_code)

This method takes only input parameters: visitorCode. Result contains only active feature flags for a given visitor.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
Return value
TypeDescription
ArrayList of feature flag keys which are active for a given visitor_code
Exceptions Thrown
TypeDescription
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

get_experiment_list

experiment_list = kameleoon_client.get_experiment_list

Returns a list of experiment IDs currently available for the SDK

Return value
TypeDescription
ArrayList of experiment's IDs

get_experiment_list_for_visitor

experiment_list_active = kameleoon_client.get_experiment_list_for_visitor(visitor_code)

only_allocated = false
experiment_list = kameleoon_client.get_experiment_list_for_visitor(visitor_code, only_allocated)

This method takes two input parameters: visitor_code and only_allocated. Returns a list of experiment IDs currently available for specific visitor_code according to the only_allocated option. If only_allocated parameter is true result contains only allocated for the user experiments, otherwise it contains all targeted experiments to specific visitor_code

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
only_allocatedBooleanThe value is true by default, result contains only allocated for the user experiments. Set false for fetching all targeted experiment IDs. This field is optional.
Return value
TypeDescription
ArrayList of experiment IDs available for specific visitor_code according to the only_allocated option

get_remote_data

kameleoon_client.get_remote_data('test') # default timeout
kameleoon_client.get_remote_data('test', 1000) # 1000 milliseconds timeout
begin
kameleoon_client.get_remote_data('test')
rescue => e
#catch error
end
note

Previously named: retrieve_data_from_remote_source - deprecated since SDK version 2.1.0 and will be removed in a future releases.

The get_remote_data() method allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in Kameleoon::ClientFactory.create()) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

Arguments
NameTypeDescription
keystringThe key that the data you try to get is associated with. This field is mandatory.
timeoutintTimeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default_timeout value from configuration file or 2000 milliseconds if it's not specified in the file.
Return value
TypeDescription
HashHash object associated with retrieving data for specific key.
Exceptions Thrown
TypeDescription
ErrorError indicating that the request timed out or retrieved data can't be parsed with JSON.parse() method

get_engine_tracking_code

engine_tracking_code = kameleoon_client.get_engine_tracking_code(visitor_code)
# The following string will be returned:
#
# window.kameleoonQueue = window.kameleoonQueue || [];
# window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
# window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
# window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
# window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);
#
# Here, experiment1ID, experiment2ID and variation1ID, variation2ID represent
# the specific experiments and variations that users have been assigned to.

Kameleoon offers built-in integrations with various analytics solutions, such as Mixpanel, GA4, Segment... To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method get_engine_tracking_code() that allows you to automatically send exposure events to the analytics solution you are using. For more information on how to implement this method, please refer to the following documentation.

note

To benefit from this feature, you will need to implement both the C# SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon Asynchronous tag, which you can install before your closing <body> tag in your HTML page, as it will be only used for tracking purposes.

Arguments
NameTypeDescription
visitor_codeStringThe user's unique identifier. This field is mandatory.
Return value
TypeDescription
StringJavasScript code to be inserted in your page

on_update_configuration


kameleoon_client.on_update_configuration(
// configuration was updated
)

The on_update_configuration() method allows you to handle the event when configuration has updated data. It takes one input parameter: callable handler. The handler that will be called when the configuration is updated using a real-time configuration event.

Arguments
NameTypeDescription
handlerCallableThe handler that will be called when the configuration is updated using a real-time configuration event.

Kameleoon::Data

Browser

kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))
NameTypeDescription
browserKameleoon::BrowserTypeList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory.

PageView

kameleoon_client.add_data(visitor_code, Kameleoon::PageView.new("https://url.com", "title", [3]))
NameTypeDescription
urlStringURL of the page viewed. This field is mandatory.
titleStringTitle of the page viewed. This field is mandatory.
referrersArrayReferrers of viewed pages. This field is optional.
note

The index (ID) of the referrer is available on our Back-Office, in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for a given site would have the ID 0, not 1.
https://help.kameleoon.com/create-acquisition-channel

Conversion

kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10, false))
NameTypeDescription
goal_idIntegerID of the goal. This field is mandatory.
revenueFloatConversion revenue. This field is optional.
negativeBooleanDefines if the revenue is positive or negative. This field is optional.

CustomData

kameleoon_client.add_data(visitor_code, Kameleoon::CustomData.new(1, "some custom value"))
NameTypeDescription
indexIntegerIndex / ID of the custom data to be stored. This field is mandatory.
valueStringValue of the custom data to be stored. This field is mandatory.
note

The index (ID) of the custom data is available on our Back-Office, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site will have the ID 0, not 1.

Interest

kameleoon_client.add_data(visitor_code, Kameleoon::Interest.new(0))
NameTypeDescription
indexIntegerIndex of interest. This field is mandatory.

Device

kameleoon_client.add_data(visitor_code, Kameleoon::Device.new(Kameleoon::DeviceType::DESKTOP))
NameTypeDescription
deviceDeviceTypeList of devices: PHONE, TABLET, DESKTOP. This field is mandatory.

UserAgent

kameleoon_client.add_data(visitor_code, Kameleoon::UserAgent.new("Your User Agent"))
NameTypeDescription
valueStringThe User-Agent value that will be sent with tracking requests. This field is mandatory.