Skip to main content
Integrating the SDK into your web app is easy, and its footprint (memory and network usage) is low. Getting started: For help getting started, see the developer guide. Latest version: 3.22.2. See the Ruby SDK changelog for release notes, or the SDK changelog index for all SDKs. SDK methods: For the full reference documentation of the Ruby SDK, see the reference section.

Developer guide

This section shows you how to integrate the SDK 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:

Configure the client

You provide credentials for the Ruby SDK using a configuration file, which you can also use to customize the SDK’s behavior. You can start with the sample configuration file. Add this file to the default path /etc/kameleoon/client-ruby.yaml. If you use another location, you must pass the path as an argument to the Kameleoon::KameleoonClientFactory.Create() method during initialization. These are the available keys in the latest SDK:
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 app and configured the correct credentials (in /etc/kameleoon/client-ruby.yaml or Kameleoon::KameleoonClientConfig), you must set up a server-side experiment in the Kameleoon App. The next step is creating the Kameleoon client in your app code. The following code provides an example of creating the Kameleoon client. A Kameleoon::KameleoonClient is a singleton object that acts as a bridge between your app and Kameleoon. It includes all the methods and properties you need to run an experiment.
Developers are responsible for ensuring the correct logic of their app code when implementing A/B testing with Kameleoon. A best practice is to always assume that a visitor may be excluded from the experiment if it hasn’t yet been launched. This practice is simple to implement, as it aligns with the default or reference variation logic, which should always be in place. The code samples in the next section demonstrate this approach.
If you use Ruby on Rails, initialize the Kameleoon client at server start-up in the app.rb file.
You can then access the Kameleoon client in your controllers:

Activating a feature flag

Assigning a unique ID to a user
To assign a unique ID to a user, you can use the get_visitor_code() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a default_visitor_code that you would have generated. The ID is then set in a response headers cookie. If you are using Kameleoon in Hybrid mode, calling the get_visitor_code() method ensures that the app file engine.js (previously named, kameleoon.js) and the SDK share the unique ID (visitor code).
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account. To determine the status or variation of a feature flag for a specific user, you should use the get_variation() or feature_active?() method to retrieve the configuration based on the feature_key. The get_variation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the feature_key and visitor_code. You can use the feature_active?() method to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options. If your feature flag has associated variables (such as specific behaviors tied to each variation) get_variation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the feature flag targets the user, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK sends the exposure event to the specified experiment on the next tracking request, which it triggers automatically based on the SDK’s tracking_interval_millisecond. The default interval is 1000 milliseconds (1 second). The get_variation() method allows you to control whether the SDK tracks the visitor. If track=false, the SDK sends no exposure events. This option is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=false is helpful when using the get_variations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the add_data() method to add these data points to the user’s profile. To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the get_remote_visitor_data() method. This method asynchronously fetches data from the servers. It’s important to call get_remote_visitor_data() before retrieving the variation or checking if the feature flag is active, because the SDK might need this data to assign a user to a given variation. To learn more about available targeting conditions, see the detailed article on the subject. Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here. If you need to track additional data points beyond what’s automatically collected, you can use Kameleoon’s Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don’t forget to call the flush() method to send the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it’s recommended to filter out bots by using the UserAgent data type.
Tracking goal conversions
When a user completes a desired action (such as making a purchase), it’s recorded as a conversion. To track conversions, use the track_conversion() method and provide the required visitor_code and goal_id parameters. The SDK sends the conversion tracking request along with the next scheduled tracking request, which occurs at regular intervals (defined by tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=true.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the get_engine_tracking_code() method. The get_engine_tracking_code() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

Error handling

Every error the SDK raises is a KameleoonError, so a single handler for that type catches every SDK failure. Handle a specific error type when your app needs to react to a particular failure, for example to fall back to your default behavior when a feature flag isn’t in the configuration or the SDK isn’t initialized yet. The reference section of each method lists the errors it can raise. Errors are raised as exceptions. All of them live in the Kameleoon::Exception module: Kameleoon::Exception::KameleoonError derives from StandardError, and every specific error derives from KameleoonError, so you can rescue a single error such as Kameleoon::Exception::FeatureNotFound, or the base KameleoonError.
SDK errors are expected behavior, not crashes: a feature flag that isn’t activated yet, an SDK that is still loading its configuration, or a network failure are all normal conditions. When feature evaluation fails, log the error and fall back to your default behavior so the visitor still gets a working experience.

Cross-device experimentation

To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor’s devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the article on cross-device experimentation.

Synchronizing custom data across devices

Although custom mapping synchronization aligns visitor data across devices, it’s not always necessary. Below are two scenarios where custom mapping sync isn’t required: Same user ID across devices If you use the same user ID consistently across all devices, the SDK handles synchronization automatically without a custom mapping sync. It’s enough to call the get_remote_visitor_data() method when you want to sync the data collected between multiple devices. Multi-server instances with consistent IDs In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with get_remote_visitor_data()) is sufficient without additional custom mapping sync. Customers who need additional data can refer to the get_remote_visitor_data() method description for further guidance. In the below code, it’s assumed that you use the same unique identifier (in this case, the visitor_code, also known as userId) consistently between the two devices for accurate data retrieval.
If you want to sync collected data in real time, you need to choose the scope Visitor for your custom data.
Device A
Device B

Using custom data for session merging

Cross-device experimentation allows for combining a visitor’s history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, use CustomData to provide a unique identifier for the visitor. For more information, see the dedicated documentation. After you enable cross-device reconciliation, calling get_remote_visitor_data() with the parameter userId retrieves all known data for a given user. Sessions with the same identifier always see the same variation in an experiment. In the Visitor view of your experiment’s results pages, these sessions will appear as a single visitor. The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. The cross-device experimentation documentation outlines these limitations. Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform. Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:
  • get_remote_visitor_data() with added UniqueIdentifier(true) - to retrieve data for all linked visitors.
  • track_conversion() or flush() with added UniqueIdentifier(true) data - to track some data for specific visitor that’s associated with another visitor.
Because the custom data you use as the identifier requires Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the get_remote_visitor_data() method on each device.
Here’s an example of how to use custom data for session merging.
In this example, the app has a login page. Since the user ID is unknown at the moment of login, the app uses an anonymous visitor identifier generated by the get_visitor_code() method. After the user logs in, the app associates the anonymous visitor with the user ID and uses it as a unique identifier for the visitor.

Using a custom bucketing key

By default, Kameleoon uses a unique, anonymous visitor ID (visitor_code) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs, and in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag. The Custom Bucketing Key option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses your specified key instead of the default visitor_code.

Use cases

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:
  • Account-level or organizational experiments: For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an accountId. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.
By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, which leads to more reliable results and a better user experience.

Technical details

When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your app’s data:
  • Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the add_data() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
For the custom bucketing key to function correctly, you must also define and configure it for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK’s bucketing won’t apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this article.
  • Bucketing logic: Once you provide a custom bucketing key through the add_data() method, all hash calculations for assigning users to variations use this newVisitorCode (your custom key) instead of the default visitor_code. Using the newVisitorCode means that the bucketing decision depends on your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
  • Data tracking and analytics: It’s crucial to note that while the newVisitorCode (your custom key) is used for bucketing decisions, the SDK sends all subsequent data (tracking events and conversions, for example) and associates it with the original visitor_code. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when you bucket at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

Technical requirements

To effectively use a custom bucketing key:
  • The key must be a String.
  • It must be unique for the entity you intend to bucket (for example, if using a userId, each user’s ID should be unique).
  • The key must be available to the SDK at the exact moment it evaluates the feature flag decision for that user or request.

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 this SDK supports, see use visit history to target users. You can also use your own external data to target users.

Logging

The SDK generates logs to reflect various internal processes and issues.

Log levels

The SDK supports configuring limiting logging by a log level.

Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.
The SDK limits logging by log level separately from the log handling logic.

Reference

This is a full reference documentation of the Ruby SDK.

Initialization

create()

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
Exceptions thrown

wait_init()

Use wait_init() when your app should wait for the Kameleoon client to finish initialization before it evaluates feature flags. The call returns the result of the configuration fetch: true when the client finishes initializing, and false if the initial configuration fetch fails before the client becomes ready. Background retries continue after that first failure. Once a retry succeeds, subsequent calls return true. If no initialization result is available before the timeout expires, the call returns false. If you don’t provide a timeout_millisecond value, the SDK uses the default timeout from default_timeout_millisecond. The failure that prevented the SDK from initializing is reported to the log.
Call wait_init() once on app startup to wait until the SDK has loaded its configuration or the timeout expires. On each incoming request, use is_ready?() as a non-blocking guard before evaluating feature flags. Even if wait_init() fails, the SDK keeps retrying the configuration fetch in the background, so is_ready?() starts returning true after a retry succeeds.
Parameters
Return value

is_ready?()

is_ready?() checks whether the SDK is ready for use, which means its configuration has been successfully loaded. Unlike wait_init(), this method returns immediately without blocking or throwing.
  • Once the SDK becomes ready, it stays ready. If a later configuration refresh fails, the SDK keeps using the previously downloaded configuration and doesn’t return to a not-ready state.
  • Call wait_init() once on app startup to wait until the SDK has loaded its configuration or the timeout expires. On each incoming request, use is_ready?() as a non-blocking guard before evaluating feature flags. Even if wait_init() fails, the SDK keeps retrying the configuration fetch in the background, so is_ready?() starts returning true after a retry succeeds.
Return value

Feature flags and variations

feature_active?()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
Previously called 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 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 they shouldn’t). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous FeatureFlag value. You must ensure 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.
The parameter is_unique_identifier is deprecated. Use UniqueIdentifier instead.The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.
The feature_active?() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Parameters
Return value
Exceptions thrown

get_variation()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
Retrieves the Variation assigned to a given visitor for a specific feature flag. This method takes a visitor_code and feature_key as mandatory arguments. The track argument is optional and defaults to true. It returns the assigned Variation for the visitor. If the visitor isn’t associated with any feature flag rules, the method returns the default Variation for the given feature flag. Ensure your code includes proper error handling to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they don’t match any predefined delivery rules for a feature flag. In other words, it’s the fallback variation applied to all users who aren’t targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
Return value
Exceptions thrown

get_variations()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
Retrieves a map of Variation objects assigned to a given visitor across all feature flags. This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitor_code as a mandatory argument, while only_active and track are optional.
  • If you set only_active to true, the method get_variations() returns feature flag variations only if the visitor isn’t bucketed with the off variation.
  • The track parameter controls whether the method tracks the variation assignments. By default, it’s true. If it’s false, the method doesn’t track variation assignments.
The returned map consists of feature flag keys as keys and their corresponding Variation as values. If the SDK assigns no variation for a feature flag, the method returns the default Variation for that flag. Implement proper error handling to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they don’t match any predefined delivery rules for a feature flag. In other words, it’s the fallback variation applied to all users who aren’t targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
Return value
Exceptions thrown

set_forced_variation()

The method allows you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. The method is especially valuable for controlled experiments where the usual evaluation logic isn’t required or you need to skip it. It can also be helpful in scenarios like debugging or custom testing. When you set a forced variation, it overrides Kameleoon’s real-time evaluation logic. The SDK skips processes like segmentation, targeting conditions, and algorithmic calculations. To preserve segmentation and targeting conditions during an experiment, set force_targeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation starts, the SDK fully processes and completes it first.
Kameleoon treats a forced variation the same as an evaluated variation. It’s tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting. The method may throw exceptions under certain conditions (for example, invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your app remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
  • Forced variations: Are specific to an individual experiment.
  • Simulated variations: Affect the overall feature flag result.
Parameters
Exceptions thrown
In most cases, you only need to handle the basic error, KameleoonError, as the example demonstrates. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, you can handle general language errors by including StandardError.

evaluate_audiences()

  • 📨 Sends Tracking Data to Kameleoon
This method evaluates visitors against all available Audiences Explorer segments and tracks those who match. Call evaluate_audiences() after you set or update all relevant visitor data, and just before getting a feature variation or checking a feature flag. This approach ensures that Kameleoon evaluates the visitor against the most current data available, allowing for accurate audience assignment based on all criteria. After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
Parameters
Exceptions thrown
In most cases, you only need to handle the basic error, KameleoonError, as the example demonstrates. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, you can handle general language errors by including StandardError.

get_data_file()

To evaluate all feature flags, use get_variations(). This method is more efficient than calling DataFile and iterating through flags with get_variation().
Returns the current SDK configuration as a DataFile object.
Return value

Visitor data

get_visitor_code()

Previously called 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 method 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. 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. default_visitor_code_ lets you use your own identifiers as visitor codes should you wish, which can have the added benefit of matching Kameleoon visitors with your own users without any additional look-ups in a matching table.
  3. If no cookie, parameter, 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 set is the value returned by the method. For more information, refer to this article.
If you provide your own visitor_code, you must guarantee its uniqueness-the SDK can’t check it. Also, note that the length of the visitor_code is limited to 255 characters. Any excess characters will throw an exception.
The get_visitor_code() method allows you to set simulated variations for a visitor. When cookies (from a request or document) contain the key kameleoonSimulationFFData, the method reads the cookie and stores the simulated variations for that visitor; its return value doesn’t change. Subsequent feature evaluations for the visitor, such as get_variation() and feature_active?(), then bypass the standard evaluation process and return the simulated Variation based on the provided data.You can apply simulations in two ways:
  • Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, Kameleoon creates the cookie automatically when you simulate a variant’s display using the Simulation Panel.
  • Manually: Set the kameleoonSimulationFFData cookie manually.
It’s important to distinguish simulated variations from forced variations:
  • Simulated variations: Affect the overall feature flag result.
  • Forced variations: Are specific to an individual experiment.
⚙️ Manual setupEnsure the kameleoonSimulationFFData cookie follows this format:
  • kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation with varId of experiment expId for the given featureKey.
  • kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in the Then, for everyone else in Production, serve section) for the given featureKey.
⚠️ To ensure the cookie value works correctly, encode it as a URI component using a method such as encodeURIComponent.
Parameters
Return value

add_data()

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 doesn’t return any value and doesn’t interact with Kameleoon backend servers on its own. Instead, the SDK saves all the declared data 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’s triggered by the flush(). The track_conversion() method also sends out any previously associated data, just like the flush(). The same holds true for get_variation() and get_variations() methods if an experimentation rule is triggered.
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.
Parameters
Exceptions

flush()

  • 📨 Sends Tracking Data to Kameleoon
flush() takes the Kameleoon data associated with the visitor and all of the data that was added previously using the add_data method, that hasn’t yet been sent when calling one of these methods, and sends a tracking request. flush() is non-blocking, as the server call is made asynchronously. flush() lets you control when the data associated with a given visitor_code is sent to the server. For instance, if you call add_data() a dozen times, it would be inefficient to send data to the server each time add_data() is invoked, so you only have to call flush() once at the end. If you specify a visitor_code, the flush() method uses it 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.
The parameter is_unique_identifier is deprecated. Use UniqueIdentifier instead.The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.
Arguments

get_remote_data()

Previously named: retrieve_data_from_remote_source - removed since SDK version 3.0.0.
The get_remote_data() method lets you retrieve data (according to a key passed as argument) for a specified siteCode (specified in Kameleoon::KameleoonClientFactory.create()) stored on a remote Kameleoon server. Usually, data is stored on remote servers using the Data API. This method, along with the availability of highly scalable servers for this purpose, provides a convenient way to store massive amounts of data that can be retrieved for each of your visitors/users.
Parameters
Return value
Exceptions thrown

get_remote_visitor_data()

get_remote_visitor_data() is an asynchronous method for retrieving Kameleoon Visits Data for the visitor_code from the Kameleoon Data API. The method stores data for other methods to use when making targeting decisions. Data obtained using this method plays an important role when you want to:
  • use data collected from other devices.
  • access a user’s history, such as previously visited pages during past visits.
  • use data that’s only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
By default, get_remote_visitor_data() automatically retrieves the latest stored custom data with scope=Visitor and attaches them to the visitor without having to call the add_data() method. It’s particularly useful for synchronizing custom data between multiple devices.
The parameter is_unique_identifier is deprecated. Use UniqueIdentifier instead.The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.
Parameters
Return value
Using parameters in get_remote_visitor_data()
The get_remote_visitor_data() method offers flexibility by letting you define various parameters when retrieving visitor data. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types. For example, suppose you want to retrieve data on visitors who completed a goal “Order transaction.” You can specify parameters within the get_remote_visitor_data() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previous_visit_amount parameter to 5 and conversions to true. The flexibility shown in this example isn’t limited to goal data. You can use parameters within the get_remote_visitor_data() method to retrieve data on a variety of visitor behaviors.
Here is the list of available Kameleoon::Types::RemoteVisitorDataFilter options:

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.
Parameters
Return value
Exceptions thrown
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 method 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.
Parameters
Exceptions thrown
Consent revocation behavior
When you call set_legal_consent() with consent=false, the SDK doesn’t delete the kameleoonVisitorCode cookie. Instead, it stops extending the cookie’s expiration date, allowing the cookie to persist until it naturally expires. If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK won’t remove the file automatically.

Goals and third-party analytics

track_conversion()

  • 📨 Sends Tracking Data to Kameleoon
Use this method to track a conversion for a specific goal and user. This method requires visitor_code and goal_id. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitor_code is usually identical to the one you used when triggering the experiment. The track_conversion() method doesn’t return any value. This method is non-blocking because the SDK makes the server call asynchronously.
The parameter isUniqueIdentifier is deprecated. Use UniqueIdentifier instead.The isUniqueIdentifier 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 session merging connects to the anonymous visitor.
Parameters
metadata values are accessible through raw data exports and the results page.If you provide the metadata parameter, Kameleoon uses these specified values for the current conversion instead of what you previously collected using the add_data() method. If you omit the parameter, Kameleoon uses the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the track_conversion() method.In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).
Exceptions

get_engine_tracking_code()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the get_engine_tracking_code() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous 5 seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration. Refer to hybrid experimentation for more information on implementing this method.
  • To use this feature, implement both the Ruby SDK and Kameleoon Engine.js. Because this flow uses Engine.js only for tracking, you can install the asynchronous tag before the closing </body> tag.
  • If you only want to track experiments in Kameleoon and don’t need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call getVisitorCode, as long as you add the corresponding experiment assignments to window.kameleoonQueue.
  • You can insert the returned tracking code directly into an HTML <script> tag.
In this example, 123456 and 234567 are experiment IDs, and 7890 and 8901 are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
Parameters
Return value

Events

set_event_handler()

Use this method to register a handler for SDK events. The SDK calls the handler when the selected event occurs. Registering a new handler for the same event type replaces the previous handler. Passing nil as the handler removes the current handler for the selected event type.
DataFileUpdateEvent contains information about an SDK data file update.
Parameters

Data types

Browser

The Browser data set stored here can be used to filter experiment and personalization reports by any value associated with it.

PageView

The referrer’s index (ID) is available in the Acquisition channel configuration page of the Back-Office. Be careful: this index starts at 0, so the first acquisition channel you create for a site would have the ID 0, not 1.

Conversion

The Conversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
  • Each visitor can have multiple Conversion objects.
  • You can find the goal_id in the Kameleoon app.

CustomData

CustomData allows any type of data to be easily associated with a visitor. You can then use it as a targeting condition in segments or as a filter/breakdown in experiment reports. To learn more about custom data, refer to this article.
  • Each visitor can only have one CustomData for each unique index. Adding another CustomData with the same index will replace the existing CustomData.
  • The custom data index can be found in the Custom Data dashboard under the “INDEX” column.
  • To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option Use this data only locally for targeting purposes when creating custom data.
  • Adding a CustomData instance created with a name when the SDK instance configuration isn’t up to date or the name isn’t registered, will result in the data being ignored.

Device

UserAgent

Store information on the visitor’s user-agent. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this vulnerability, 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, pass the value curl/8.0 of the userAgent to exclude them from your analytics.

UniqueIdentifier

If you don’t add UniqueIdentifier for a visitor, visitor_code is used as the unique visitor identifier, which is useful for Cross-device experimentation. When you add UniqueIdentifier for a visitor, the SDK links the flushed data to the visitor associated with the specified identifier. The UniqueIdentifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.

OperatingSystem

OperatingSystem contains information about the visitor’s operating system.
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first.
Cookie contains information about the cookie stored on the visitor’s device.
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first.

Geolocation

Geolocation contains the visitor’s geolocation details.
  • Each visitor can have only one Geolocation. Adding a second Geolocation overwrites the first one.

ApplicationVersion

ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.

Returned types

DataFile

The DataFile contains the SDK configuration details. It can be extended with additional information if required by clients. If you need more details, contact your Customer Success Manager.

FeatureFlag

The FeatureFlag represents a set of properties that define a feature flag itself (for example, its Variations, Rules, environment status, and other related details). It can be extended with additional information if required by clients. If you need more details, contact your Customer Success Manager.

Rule

The Rule represents a set of properties that define a rule itself (for example, its Variations). It can be extended with additional information if required by clients. If you need more details, contact your Customer Success Manager.

Variation

Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
  • The Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
  • Ensure that your code handles the case where id or experiment_id may be nil, indicating a default variation.
  • The variables hash might be empty if no variables are associated with the variation.

Variable

Variable contains information about a variable associated with the assigned variation.

Deprecated methods

These methods are deprecated and will be removed in SDK version 4.0.0.

get_feature_variation_key()

  • 📨 Sends Tracking Data to Kameleoon
Use get_variation() instead.
To get a feature variation key, call the get_feature_variation_key method. This method takes a visitor_code and feature_key as mandatory arguments to get a user’s variation key. 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 doesn’t match any of the rules, the default value will be returned, which you can define in your account. You must ensure 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.
The parameter is_unique_identifier is deprecated. Use UniqueIdentifier instead.The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.
Parameters
Return value
Exceptions thrown

get_active_feature_list_for_visitor()

This method only takes visitorCode as an input parameter. The result only contains active feature flags for a given visitor.
Arguments
Return value
Exceptions thrown

get_active_features()

get_active_features method retrieves information about the active feature flags that are available for the specified visitor code.
This method is deprecated and will be removed in SDK version 4.0.0. Use get_variations() instead.
Arguments
Return value
Exceptions thrown

get_feature_variable()

  • 📨 Sends Tracking Data to Kameleoon
Use get_variation() instead.
Previously called obtain_feature_variable - deprecated since SDK version 2.1.0 and will be removed in a future releases.
To get a variable of the variation key associated with a user, call the get_feature_variable method. This method takes a visitor_code, feature_key and variable_name as mandatory arguments to get a variable of the 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 the previously associated variation. If the user doesn’t match any of the rules, the default variable will be returned. You must ensure 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 to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Use UniqueIdentifier instead.The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you have access to an internal ID that’s connected to the anonymous visitor using session merging capabilities.
Parameters
Return value
Exceptions thrown

get_feature_variation_variables()

Use get_variation() instead.
To retrieve the all feature variables, call the get_feature_variation_variables method. A feature variable can be changed using the Kameleoon web app. 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. It throws an error (FeatureNotFound) if the requested feature flag hasn’t been found in the SDK’s client configuration. If the variation key isn’t found, the method throws (FeatureVariationNotFound) error.
Parameters
Return value
Exceptions thrown

get_feature_list()

Returns a list of feature flag keys available for the SDK.
Return value

on_update_configuration()

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