Skip to main content

Ruby SDK

With the Ruby SDK, you can run experiments and activate feature flags on your back-end Ruby server. Integrating our SDK into your web-application is easy, and its footprint (memory and network usage) is low.

Getting started: For help getting started, see the developer guide.

Changelog: Latest version of the Ruby SDK: 3.3.0 Changelog.

Reference

This is a full reference documentation of the Ruby SDK.

Initialization

create()

kameleoon_config = Kameleoon::KameleoonClientConfig.new('client-id', 'client-secret')
kameleoon_client = Kameleoon::KameleoonClientFactory.create('a8st4f59bj', config: kameleoon_config)

kameleoon_client = Kameleoon::KameleoonClientFactory.create('a8st4f59bj', config_path: '/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::KameleoonClient, 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.
configKameleoon::KameleoonClientConfigConfiguration SDK object that you can pass instead of using a configuration file. This field is optional.
Exceptions thrown
TypeDescription
Kameleoon::Exception::SiteCodeIsEmptyException indicating that the specified site code is empty string which is invalid value.

wait_init()

kameleoon_client = Kameleoon::KameleoonClientFactory.create('a8st4f59bj')

if kameleoon_client.wait_init
# The SDK has been initialized, you can fetch a feature flag / experiment configuration here.
end

wait_init awaits the initialization of the Kameleoon client. This method allows you to check if the client has been successfully initialized before proceeding with other operations.

Return value
TypeDescription
Booltrue if the Kameleoon client instance was successfully initialized, otherwise false.

Feature flags and variations

feature_active?()

  • 📨 Sends Tracking Data to Kameleoon
visitor_code = kameleoon_client.get_visitor_code(cookies)

feature_key = "new_checkout"
has_new_checkout = false

begin
has_new_checkout = kameleoon_client.feature_active?(visitor_code, feature_key, is_unique_identifier: false)
rescue Kameleoon::Exception::FeatureNotFound
# 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 - removed since SDK version 3.0.0.

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.

If you specify a visitor_code, the feature_active? method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The is_unique_identifier can also be useful in other scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

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.
is_unique_identifierBooleanWhen set to true, the SDK links the flushed data with the visitor associated with the specified identifier.
Return value
TypeDescription
BooleanValue of the feature that is registered for a given visitor_code.
Exceptions thrown
TypeDescription
Kameleoon::Exception::FeatureNotFoundException 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()

  • 📨 Sends Tracking Data to Kameleoon
visitor_code = kameleoon_client.get_visitor_code(cookies)

feature_key = "feature_key"
variation_key = ""

begin
variation_key = kameleoon_client.get_feature_variation_key(visitor_code, feature_key, is_unique_identifier: false)
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::FeatureNotFound
# 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
rescue Kameleoon::Exception::FeatureEnvironmentDisabled
# The feature is disabled for the environment
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.

If you specify a visitor_code, the get_feature_variation_key method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The is_unique_identifier is also useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

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.
is_unique_identifierBooleanWhen true, the SDK links the flushed data with the visitor associated with the specified identifier.
Return value
TypeDescription
stringVariation key of the feature flag that is registered for a given visitor_code.
Exceptions thrown
TypeDescription
Kameleoon::Exception::FeatureNotFoundException 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::FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

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)
note

This method is deprecated and will be removed in SDK version 4.0.0. Use get_active_features() instead.

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_active_features()

active_features = kameleoon_client.get_active_features(visitor_code)

get_active_features method retrieves information about the active feature flags that are available for the specified visitor code.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
Return value
TypeDescription
HashA hash that contains the assigned variations of the active features using the active feature IDs as keys.
Exceptions thrown
TypeDescription
Kameleoon::Exception::VisitorCodeNotValidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

Variables

get_feature_variable()

  • 📨 Sends Tracking Data to Kameleoon
visitor_code = kameleoon_client.get_visitor_code(cookies)

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

begin
variable_value = kameleoon_client.get_feature_variable(visitor_code, feature_key, variable_name, is_unique_identifier: false)
# 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::FeatureNotFound
# 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::FeatureEnvironmentDisabled
# The feature is disabled for the environment
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.

If you specify a visitor_code, the get_feature_variable method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

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.
is_unique_identifierBooleanWhen true, the SDK links the flushed data with the visitor associated with the specified identifier.
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::FeatureNotFoundException 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::FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
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_feature_variation_variables()

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

begin
data = kameleoon_client.get_feature_variation_variables(feature_key, variable_key)
rescue Kameleoon::Exception::FeatureNotFound
# The feature is not yet activated on Kameleoon's side
rescue Kameleoon::Exception::FeatureVariationNotFound
# Requested variation not defined on Kameleoon's side
rescue Kameleoon::Exception::FeatureEnvironmentDisabled
# The feature is disabled for the environment
end

To retrieve the all feature variables, call the get_feature_variation_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 (FeatureNotFound) 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 (FeatureVariationNotFound) 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::FeatureNotFoundException 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::FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
Kameleoon::Exception::FeatureVariationNotFoundException 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.

Visitor data

get_visitor_code()

require "securerandom"

visitor_code = kameleoon_client.get_visitor_code(cookies)

visitor_code = kameleoon_client.get_visitor_code(cookies, visitor_code)

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

Previously named: obtain_visitor_code - removed since SDK version 3.0.0.

Call the get_visitor_code helper method to obtain the Kameleoon visitor_code for the current visitor. This is important when using Kameleoon in a mixed front-end and back-end environment, where user identification accuracy must be guaranteed. The implementation logic is as follows:

  1. First, check for a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request. If found, use this as the visitor identifier.

  2. If no cookie or parameter is found, check for the default_visitor_code argument. If found, use this as the identifier. 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. If no cookie, paramater, or argument is found, randomly generate a unique identifier.

In all cases, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. In later visits, the identifier that you sets is the the value 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.
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.

add_data()

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(cookies)

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))

The add_data() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.

The add_data() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the flush method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush. Note that the track_conversion method also sends out any previously associated data, just like the flush method. The same is true for get_feature_variation_key and get_feature_variable methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.

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()

  • 📨 Sends Tracking Data to Kameleoon
require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(cookies)

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, is_unique_identifier: false)

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 feature_active?, get_feature_variation_key(), get_feature_variable(), 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.

If you specify a visitor_code, the flush method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

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.
is_unique_identifierBooleanWhen true, the SDK links the flushed data with the visitor associated with the specified identifier.

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 - removed since SDK version 3.0.0.

The get_remote_data() method allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in Kameleoon::KameleoonClientFactory.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.
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_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_remote_visitor_data()

The get_remote_visitor_data method allows you to retrieve custom data stored on remote Kameleoon servers for a visitor (specified using the visitor_code argument). If add_data is true, this method automatically adds the retrieved data to a visitor without requiring you to make a separate add_data call.

You must have previously stored data on our remote servers, which you can add with any of the following tracking calls in the SDK:

  • flush
  • get_feature_variation_key
  • get_feature_variable
  • feature_active?

Using the get_remote_visitor_data method along with the availability of our highly scalable servers provides a convenient way to quickly access and synchronize large amounts of data across all of the visitor's devices.

If you specify a visitor_code, the get_remote_visitor_data method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codeStringThe visitor code for which you want to retrieve the assigned data. 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_timeout value from configuration file or 2000 milliseconds if it's not specified in the file.
add_dataBooleanA boolean indicating whether the method should automatically add retrieved data for a visitor. If not specified, the default value is true. This field is optional.
filterKameleoon::Types::RemoteVisitorDataFilterFilter that specifies which data should be retrieved from visits. By default, only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter.new(previousVisitAmount: 1, currentVisit: true, customData: true) or RemoteVisitorDataFilter.new). Other filters parameters are set to false. This field is optional.
is_unique_identifierBooleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
note

Here is the list of available Kameleoon::Types::RemoteVisitorDataFilter options:

NameTypeDescriptionDefault
previousvisit_amount (_optional)IntegerNumber of previous visits to retrieve data from. Number between 1 and 251
currentvisit (_optional)BooleanIf true, current visit data will be retrievedtrue
customdata (_optional)BooleanIf true, custom data will be retrieved.true
pageviews (_optional)BooleanIf true, page data will be retrieved.false
geolocation (optional)BooleanIf true, geolocation data will be retrieved.false
device (optional)BooleanIf true, device data will be retrieved.false
browser (optional)BooleanIf true, browser data will be retrieved.false
operatingsystem (_optional)BooleanIf true, operating system data will be retrieved.false
conversions (optional)BooleanIf true, conversion data will be retrieved.false
experiments (optional)BooleanIf true, experiment data will be retrieved.false
kcs (optional)BooleanIf true, KCS heat data will be retrieved.false
Return value
TypeDescription
ArrayAn array of data assigned to the given visitor.

Example code

    visitor_code = 'visitorCode'

# Visitor data will be fetched and automatically added for `visitor_code`
data_array = kameleoon_client.get_remote_visitor_data(visitor_code) # default timeout
data_array = kameleoon_client.get_remote_visitor_data(visitor_code, 1000) # 1 second timeout

# If you only want to fetch data and add it yourself manually, set `add_data` to `false`
data_array = kameleoon_client.get_remote_visitor_data(visitor_code, add_data: false) # default timeout
data_array = kameleoon_client.get_remote_visitor_data(visitor_code, 1000, add_data: false) # 1 second timeout

# If you want to fetch custom list of data types
filter = RemoteVisitorDataFilter(25, customData: false, conversions: true, experiments: true)
data_array = kameleoon_client.get_remote_visitor_data(visitor_code, filter: filter)

# If you want to the SDK link the extracted data with the visitor associated with the specified identifier.
data_array = kameleoon_client.get_remote_visitor_data(visitor_code, is_unique_identifier: true)

get_visitor_warehouse_audience()

Retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

Arguments
NameTypeDescription
visitor_codeStringA unique visitor identification string, can't exceed 255 characters length.
custom_data_indexIntegerAn integer representing the index of the custom data you want to use to target your BigQuery Audiences.
warehouse_keyStringA unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
timeoutIntegerTimeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional. If not provided, the default value is 10000 milliseconds.
Return value
TypeDescription
Kameleoon::CustomDataA CustomData instance confirming that the data has been added to the visitor.
Exceptions thrown
TypeDescription
Kameleoon::Exception::VisitorCodeInvalidException indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters).
StandardErrorException indicating that the request timed out or any other reason of failure.
Example code
begin
warehouse_audience_data = kameleoon_client.
get_visitor_warehouse_audience(visitor_code, custom_data_index) # default timeout
warehouse_audience_data = kameleoon_client.
get_visitor_warehouse_audience(visitor_code, custom_data_index, 1000) # 1 second timeout

warehouse_audience_data = kameleoon_client.
get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key: warehouse_key) # default timeout
warehouse_audience_data = kameleoon_client.
get_visitor_warehouse_audience(visitor_code, custom_data_index, 1000, warehouse_key: warehouse_key) # 1 second timeout

# Your custom code
rescue => e
# Handle exception
end
visitor_code = kameleoon_client.get_visitor_code(cookies)
kameleoon_client.set_legal_consent(visitor_code, true, cookies)

You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the consent parameter to false limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.

Arguments
NameTypeDescription
visitor_codeStringThe user's unique identifier. This field is required.
consentBoolA boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. This field is required.
cookiesHashThe HTTP response where values in the cookies will be adjusted based on the legal consent status. This field is optional.
Exceptions thrown
TypeDescription
Kameleoon::Exception::VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

Goals and third-party analytics

track_conversion()

  • 📨 Sends Tracking Data to Kameleoon
require "kameleoon"
require "kameleoon/data/page_view"
require "kameleoon/data/browser"
require "kameleoon/data/conversion"

visitor_code = kameleoon_client.get_visitor_code(cookies)
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_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10, false))
kameleoon_client.track_conversion(visitor_code, goal_id, is_unique_identifier: false)

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.

If you specify a visitor_code, the track_conversion method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

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.
is_unique_identifierBooleanWhen true, the SDK links the flushed data with the visitor associated with the specified identifier.

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, Google Analytics 4, 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. The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last 5 seconds. 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
StringJavaScript code to be inserted in your page

Events

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.

Data types

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.

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

custom_data = Kameleoon::CustomData.new(1, 'value1', 'value2')

custom_data = Kameleoon::CustomData.new({ 'id' => 1, 'values' => ['value1', 'value2'] })

kameleoon_client.add_data(visitor_code, custom_data)
NameTypeDescription
idIntegerIndex / ID of the custom data to be stored. This field is mandatory.
valuesArrayValues 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.

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.

Store information on the user-agent of the visitor. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.

If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.

OperatingSystem

OperatingSystem contains information about the operating system on the visitor's device.

note

Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.

NameTypeDescription
typeOperatingSystemTypeList of types: WINDOWS, MAC, IOS, LINUX, ANDROID, WINDOWS_PHONE. This field is mandatory.
kameleoon_client.add_data(visitor_code, Kameleoon::OperatingSystem.new(Kameleoon::OperatingSystemType::ANDROID))

Cookie contains information about the cookie stored on the visitor's device.

note

Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.

NameTypeDescription
cookiesHashHash object ({:cookie_name => cookie_value}) consisting of cookie keys and values. This field is mandatory.
cookie = Kameleoon::Cookie.new({ "k1" => "v1", "k2" => "v2" })
kameleoon_client.add_data(visitor_code, cookie)

Geolocation

Geolocation contains the visitor's geolocation details.

note

Each visitor can only have one Geolocation. Adding a second Geolocation overwrites the first one.

NameTypeDescription
countryStringThe country of the visitor. The field is required.
regionStringThe region of the visitor. The field is optional.
cityStringThe city of the visitor. The field is optional.
postalCodeStringThe postal code of the visitor. The field is optional.
latitudeFloatThe latitude of position of the visitor. Coordinate number represents decimal degrees. The field is optional.
longitudeFloatThe longitude of position of the visitor. Coordinate number represents decimal degrees. The field is optional.
kameleoon_client.add_data(visitor_code, Kameleoon::Geolocation.new("France", "Île-de-France", "Paris"))

Developer guide

This section shows you how to integrate our SDK in a few minutes and start running experiments in your Ruby applications. Follow this tutorial to set up a simple A/B test to change the number of recommended products based on different variations.

Getting Started

Install the SDK

Install the SDK using a standard gem package, which is hosted on the official RubyGems repository. To install, run the following command:

gem install kameleoon-client-ruby

Configure the client

You provide credentials for the Ruby SDK using a configuration file, which can also be used to customize the SDK's behavior. You can start with our sample configuration file. We recommend adding this file to the default path of /etc/kameleoon/client-ruby.yaml. If you use another location, you need to pass the path as an argument to the Kameleoon::KameleoonClientFactory.Create() method during initialization. These are the available keys in the latest SDK:

  • client_id: a client_id is required for authentication to the Kameleoon service. Refer to API credentials for help finding your client_id.
  • client_secret: a client_secret is required for authentication to the Kameleoon service. Refer to API credentials for help finding your client_secret.
  • refresh_interval_minute: 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.
  • session_duration_minute: sets the time interval that Kameleoon stores the visitor and their associated data in memory (RAM). Note that increasing the session duration increases the amount of RAM that needs to be allocated to store visitor data. The default session duration is 30 minutes.
  • default_timeout_millisecond: this specifies the timeout, in milliseconds for network requests of SDK. The default value is 2 seconds. Some methods have their own parameters for timeouts, but if you do not specify them explicitly, this value is used.
  • top_level_domain: the current top-level domain for your website. Use the format: example.com. Don't use https://, www, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory.
  • 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
  • verbose_mode: boolean value (true or false) that turns on additional logging, including network requests and debug information.
note

The Kameleoon Ruby SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.

Initialize the client

After you've installed the SDK into your application and configured the correct credentials (in /etc/kameleoon/client-ruby.yaml or Kameleoon::KameleoonClientConfig), you need to set up a server-side experiment in the Kameleoon App.

The next step is to create the Kameleoon client in your application code.The following code gives a clear example. A Kameleoon::KameleoonClient 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' responsibility 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.

# external settings file
require "kameleoon"

site_code = "a8st4f59bj"

kameleoon_client = Kameleoon::KameleoonClientFactory.create(site_code)

kameleoon_client = Kameleoon::KameleoonClientFactory.create(site_code, config_path: '/etc/kameleoon/client-ruby.yaml')

# internal KameleoonClientConfig object
require 'kameleoon'
require 'kameleoon/kameleoon_client_config'

kameleoon_config = Kameleoon::KameleoonClientConfig.new(
'client-id', # required
'client-secret', # required
refresh_interval_minute: configuration_refresh_interval, # (in minutes) optional, default: 60 minutes
session_duration_minute: session_duration, # (in minutes) optional, default: 30 minutes
default_timeout_millisecond: default_timeout, # (in milliseconds) optional, default: 2000 milliseconds
environment: environment, # optional, possible values: "production" / "staging" / "development" / "staging", default: "production"
top_level_domain: 'example.com',
verbose_mode: verbose_mode # optional, default: false
)
kameleoon_client = Kameleoon::KameleoonClientFactory.create(site_code, config: kameleoon_config)

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

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::KameleoonClientFactory.create(site_code)
end
end
end
end

You can then access the Kameleoon client in your controllers:

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

Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions supported by this SDK, see use visit history to target users.

You can also use your own external data to target users.