> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby SDK

> Integrate the Kameleoon Ruby SDK to run experiments and activate feature flags on Ruby back-end servers and Rails applications.

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](#developer-guide).

**Changelog**: Latest version of the Ruby SDK: 3.20.0 [Changelog](https://github.com/Kameleoon/client-ruby/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the Ruby SDK, see the [reference](#reference) section.

## Developer guide

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

```cli theme={null}
gem install kameleoon-client-ruby
```

#### 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 our [sample configuration file](/assets/developer-docs/sdks/web-sdks/client-configs/client-ruby.yaml). We recommend adding 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:

| Key                                                                             | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Default value        |
| ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `client_id` <Badge color="red" size="sm">required</Badge>                       | Required for authentication to the Kameleoon service. To find your **client id**, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                                                                                                                                                                                                                                                                         |                      |
| `client_secret` <Badge color="red" size="sm">required</Badge>                   | Required for authentication to the Kameleoon service. To find your **client secret**, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                                                                                                                                                                                                                                                                     |                      |
| `session_duration_minute` <Badge color="green" size="sm">optional</Badge>       | Designates the predefined 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.                                                                                                                                                                                                                                                                                                                                                                                 | `30` minutes         |
| `refresh_interval_minute` <Badge color="green" size="sm">optional</Badge>       | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. Additionally, we offer a [streaming mode](/developer-docs/feature-experimentation/technical-reference/technical-considerations/#streaming-premium-option) that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply new configurations in real-time, without any delays. | `60` minutes         |
| `default_timeout_millisecond` <Badge color="green" size="sm">optional</Badge>   | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value.                                                                                                                                                                                                                                                    | `10000` milliseconds |
| `tracking_interval_millisecond` <Badge color="green" size="sm">optional</Badge> | Specifies the interval for tracking requests in milliseconds. All visitors who Kameleoon evaluated for any feature flag or had data flushed are included in this tracking request, which the SDK performs once per interval. The minimum value is `1000` ms, which is also the default, and the maximum value is `5000` ms.                                                                                                                                                                                                                                                                                                  | `1000` milliseconds  |
| `environment` <Badge color="green" size="sm">optional</Badge>                   | Environment from which the feature flag’s configuration is to be used. The value can be `production`, `staging`, `development`. See the [managing environments](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/manage-environments) article for details.                                                                                                                                                                                                                                                                                                                                  | `production`         |
| `top_level_domain` *(required in hybrid mode)*                                  | The current top-level domain for your website . Use the format: `example.com`. Don't include `https://`, `www`, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain.                                                                                                                                                                                                                                                                                                                                                                                                | `nil`                |
| `network_domain` <Badge color="green" size="sm">optional</Badge>                | Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon's value.                                                                                                                                                                                                                                                                                                                                                                                                                                           | `nil`                |
| `verbose_mode` *(deprecated)*                                                   | Boolean value (`true` or `false`) that turns on additional logging, including network requests and debug information. This field is deprecated and will be removed in SDK version `4.0.0`. Use [`KameleoonLogger.setLogLevel`](#log-levels) instead.                                                                                                                                                                                                                                                                                                                                                                         | `nil`                |

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

#### 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 must set up a server-side experiment in the Kameleoon App.

The next step is creating the Kameleoon client in your application 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 application and Kameleoon. It includes all the methods and properties you need to run an experiment.

<Note>
  Developers are responsible for ensuring the correct logic of their application 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 has not 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.
</Note>

```ruby theme={null}
# 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
  tracking_interval_millisecond: tracking_interval, # (in milliseconds) optional (1000 ms by default)
  environment: environment, # optional, possible values: "production" / "staging" / "development" / "staging", default: "production"
  top_level_domain: 'example.com',
  verbose_mode: verbose_mode, # optional, default: false
  network_domain: 'example.com' # optional
)
kameleoon_client = Kameleoon::KameleoonClientFactory.create(site_code, config: kameleoon_config)
```

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

```ruby theme={null}
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'
            kameleoon_config = Kameleoon::KameleoonClientConfig.new('client_id', 'client_secret')
	        config.kameleoon_client = Kameleoon::KameleoonClientFactory.create(site_code, config: kameleoon_config)
        end
	  end
  end
end
```

You can then access the Kameleoon client in your controllers:

```ruby theme={null}
class YourController < ApplicationController
  def index
    kameleoon_client = App::Application.config.kameleoon_client
    # Your controller code, using the kameleoon_client
  end
end
```

#### 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()`](#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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation), calling the `get_visitor_code()` method ensures that the unique ID (**visitor code**) is shared between the application file `engine.js` (previously named, `kameleoon.js`) and the SDK.

##### 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()`](#get_variation) or [`feature_active?()`](#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`.

The `feature_active?()` method can be used if you want 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`](#variation) object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When `track=true`, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s [`tracking_interval_millisecond`](#configure-the-client). By default, this interval is set to 1000 milliseconds (1 second).

The `get_variation()` method allows you to control whether tracking is done. If `track=false`, no exposure events will be sent by the SDK. This 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](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### 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()`](#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()`](#get_remote_visitor_data) method. This method asynchronously fetches data from the servers. It is important to call `get_remote_visitor_data()` *before* retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.

To learn more about available targeting conditions, see the [detailed article on the subject](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

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](/user-manual/experiment-analytics/analyze-results/results-page-settings#breakdown-audience).

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's [Custom Data feature](#customdata). Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the [`flush()`](#flush) method to send the collected data to Kameleoon servers for analysis.

<Note>
  To ensure your results are accurate, it's recommended to filter out bots by using the [`UserAgent`](#useragent) data type.
</Note>

##### Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the [`track_conversion()`](#track_conversion) method and provide the required `visitor_code` and `goal_id` parameters.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by [`tracking_interval_millisecond`](#configure-the-client)). If you prefer to send the request immediately, use the [`flush()`](#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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/). Then, use the [`get_engine_tracking_code()`](#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.

### 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](/developer-docs/cross-device-experimentation).

#### Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

**Same user ID across devices**
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is 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()`](#get_remote_visitor_data) method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the `visitor_code`, which can also be referred to as `userId`) is used consistently between the two devices for accurate data retrieval.

<Note>
  If you want to sync collected data in real time, you need to choose the scope **Visitor** for your custom data.
</Note>

```ruby title="Device A" theme={null}
# In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90

kameleoon_client.add_data(visitor_code, CustomData.new(VISITOR_SCOPE_CUSTOM_DATA_INDEX, 'your data'))
kameleoon_client.flush(visitor_code)
```

```ruby title="Device B" theme={null}
# Before working with the data, call `get_remote_visitor_data`.
kameleoon_client.get_remote_visitor_data(visitor_code)

# After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
# So, "your data" will be available to target and track the visitor.
```

#### Using custom data for session merging

[Cross-device experimentation](/developer-docs/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`](#customdata) to provide a unique identifier for the visitor. For more information, see the [dedicated documentation](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

After cross-device reconciliation is enabled, calling [`get_remote_visitor_data()`](#get_remote_visitor_data) with the parameter `userId` retrieves all known data for a given user.

Sessions with the same identifier will always be shown 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. These limitations are outlined [here](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Follow the [activating cross-device history reconciliation](#cross-device-experimentation) 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()`](#track_conversion) or [`flush()`](#flush) with added `UniqueIdentifier(true)` data - to track some data for specific visitor that is associated with another visitor.

<Tip>
  As the custom data you use as the identifier must be set to **Visitor scope**, you need to use [cross-device custom data synchronization](/developer-docs/cross-device-experimentation) to retrieve the identifier with the [`get_remote_visitor_data()`](#get_remote_visitor_data) method on each device.
</Tip>

Here's an example of how to use custom data for session merging.

```ruby theme={null}
# In this example, `91` represents the Custom Data's index configured as a unique identifier in Kameleoon.
MAPPING_INDEX = 91
FEATURE_KEY = 'ff123'

# 1. Before the visitor is authenticated

# Retrieve the variation for an unauthenticated visitor.
# Assume `anonymous_visitor_code` is the randomly generated ID for that visitor.
anonymous_variation = kameleoon_client.get_variation(anonymous_visitor_code, FEATURE_KEY)

# 2. After the visitor is authenticated

# Assume `user_id` is the visitor code of the authenticated visitor.
kameleoon_client.add_data(anonymous_visitor_code, CustomData.new(MAPPING_INDEX, user_id))
kameleoon_client.flush(anonymous_visitor_code, instant: true)

# Indicate that `user_id` is a unique identifier.
kameleoon_client.add_data(user_id, UniqueIdentifier.new(True))

# 3. After the visitor has been authenticated

# Retrieve the variation for the `user_id`, which will match the anonymous visitor code's variation.
user_variation = kameleoon_client.get_variation(user_id, FEATURE_KEY)
is_same_variation = user_variation.key == anonymous_variation.key # true

# The `user_id` and `anonymous_visitor_code` are now linked and tracked as a single visitor.
kameleoon_client.track_conversion(user_id, 123, 10.0)

# Additionally, the linked visitors will share all fetched remote visitor data.
kameleoon_client.get_remote_visitor_data(user_id)
```

In this example, the application has a login page. Since the user ID is unknown at the moment of login, an anonymous visitor identifier generated by the [`get_visitor_code()`](#get_visitor_code) method is used. After the user logs in, the anonymous visitor is associated with the user ID and used 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—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, leading 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 application's data:

```ruby theme={null}
bucketing_key = Kameleoon::CustomData.new(index, 'new_visitor_code')

kameleoon_client.add_data(visitor_code, bucketing_key)
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`add_data()`](#add_data) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `newVisitorCode` refers to the identifier you wish to use for your bucketing (for example, the new `userId` or `accountId`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `add_data()` method, all hash calculations for assigning users to variations will use this `newVisitorCode` (your custom key) instead of the default `visitor_code`. Using the `newVisitorCode` means that the bucketing decision is tied to 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, **all subsequent data (tracking events and conversions, for example) is sent and associated 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 bucketing is performed 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 the feature flag decision is evaluated 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](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-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.

```ruby theme={null}
require 'kameleoon/logging/kameleoon_logger'

# The `NONE` log level does not allow logging.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::NONE

# The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::ERROR

# The `WARNING` log level allows logging issues which may require additional attention.
# It extends the `ERROR` log level.
# The `WARNING` log level is a default log level.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::WARNING

# The `INFO` log level allows logging general information on the SDK's internal processes.
# It extends the `WARNING` log level.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::INFO

# The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
# with more granular diagnostic output.
# This information is not intended for end-user interpretation but can be sent to our support team
# to assist with internal troubleshooting.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::DEBUG
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```ruby theme={null}
require 'logger'
require 'kameleoon/logging/logger'

module Kameleoon
  class CustomLogger < Kameleoon::Logging::Logger
    def initialize
      @internal_logger = Logger.new(STDOUT)
    end

    def log(level, message)
      case level
      when Kameleoon::Logging::LogLevel::ERROR
        @internal_logger.error(message)
      when Kameleoon::Logging::LogLevel::WARNING
        @internal_logger.warn(message)
      when Kameleoon::Logging::LogLevel::INFO
        @internal_logger.info(message)
      when Kameleoon::Logging::LogLevel::DEBUG
        @internal_logger.debug(message)
      end
    end
  end
end


# Log level filtering is applied separately from log handling logic.
# The custom logger will only accept logs that meet or exceed the specified log level.
# Ensure the log level is set correctly.
Kameleoon::Logging::KameleoonLogger.log_level = Kameleoon::Logging::LogLevel::DEBUG # Optional, defaults to `Kameleoon::Logging::LogLevel::WARNING`.
Kameleoon::Logging::KameleoonLogger.logger = CustomLogger.new
```

## 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.

```ruby theme={null}
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')
```

##### Arguments

| Name                      | Type                             | Description                                                                                                                                      |
| ------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| site\_code                | String                           | This is a [unique key](/user-manual/faq#how-do-i-find-my-sitecode) of the Kameleoon project you are using with the SDK. This field is mandatory. |
| configuration\_file\_path | String                           | Path to the SDK configuration file. This field is optional, and set to `/etc/kameleoon/client-ruby.yaml` by default.                             |
| config                    | Kameleoon::KameleoonClientConfig | Configuration SDK object that you can pass instead of using a configuration file. This field is optional.                                        |

##### Exceptions thrown

| Type                                  | Description                                                                          |
| ------------------------------------- | ------------------------------------------------------------------------------------ |
| Kameleoon::Exception::SiteCodeIsEmpty | Exception indicating that the specified site code is empty string, which is invalid. |

#### wait\_init()

`wait_init` awaits the Kameleoon client's initialization. This method lets you check if the client has been successfully initialized before proceeding with other operations.

```ruby theme={null}
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
```

##### Return value

| Type      | Description                                                                              |
| --------- | ---------------------------------------------------------------------------------------- |
| `Boolean` | `true` if the Kameleoon client instance was successfully initialized, otherwise `false`. |

### Feature flags and variations

#### feature\_active?()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

<Note>
  Previously called `activate_feature` - removed since SDK version `3.0.0`.
</Note>

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](/developer-docs/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 parameter `is_unique_identifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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)
	# disabling tracking
	has_new_checkout = kameleoon_client.feature_active?(visitor_code, feature_key, track: false)
rescue Kameleoon::Exception::FeatureNotFound
	# The user will not be counted in the experiment, but should see the reference variation.
	has_new_checkout = false
end

if has_new_checkout
	# Implement new checkout code here
end
```

<Warning>
  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**.
</Warning>

##### Parameters

| Name                                | Type      | Description                                                                                                 |
| ----------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------- |
| visitor\_code                       | `String`  | Unique identifier of the user. This field is mandatory.                                                     |
| feature\_key                        | `String`  | Key of the feature you want to expose to a user. This field is mandatory.                                   |
| is\_unique\_identifier (Deprecated) | `Boolean` | When set to `true`, the SDK links the flushed data to the visitor associated with the specified identifier. |
| track                               | `Boolean` | An optional parameter to enable or disable tracking of the feature evaluation (`true` by default).          |

##### Return value

| Type      | Description                                                            |
| --------- | ---------------------------------------------------------------------- |
| `Boolean` | Value of the feature that is registered for a given **visitor\_code**. |

##### Exceptions thrown

| Type                                     | Description                                                                                                                                                                                                                                                                                                       |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Kameleoon::Exception::FeatureNotFound    | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception 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::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters).                                                                                                                                                                                                            |

#### get\_variation()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves the [`Variation`](#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 is not associated with any feature flag rules, the method returns the default `Variation` for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```ruby theme={null}
feature_key = "new_checkout"

begin
  variation = kameleoon_client.get_variation(visitor_code, feature_key)
  # disabling tracking
  variation = kameleoon_client.get_variation(visitor_code, feature_key, track: false)
rescue Kameleoon::Exception::FeatureNotFound
  # The error has occurred; the feature flag isn't found in the current configuration.
rescue Kameleoon::Exception::FeatureEnvironmentDisabled
  # The feature flag is disabled for the environment
rescue Kameleoon::Exception::VisitorCodeInvalid
  # The visitor code you passed to the method is invalid and can't be accepted by SDK
end

# Fetch a variable value for the assigned variation
title = variation.variables['title'].value

case variation.key
when 'on'
  # Main variation key is selected for visitorCode
when 'alternative_variation'
  # Alternative variation key
else
  # Default variation key
end
```

##### Parameters

| Name                                                         | Type     | Description                                                                    | Default |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------ | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor.                                              |         |
| `feature_key` <Badge color="red" size="sm">required</Badge>  | `String` | Key of the feature you want to expose to a visitor.                            |         |
| `track` <Badge color="green" size="sm">optional</Badge>      | `Bool`   | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type        | Description                                                                           |
| ----------- | ------------------------------------------------------------------------------------- |
| `Variation` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag. |

##### Exceptions thrown

| Type                         | Description                                                                                                                                                                                                                                                           |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`         | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |
| `FeatureNotFound`            | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `FeatureEnvironmentDisabled` | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                          |

#### get\_variations()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves a map of [`Variation`](#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 `only_active` is set to `true`, the method `get_variations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding `Variation` as values. If no variation is assigned for a feature flag, the method returns the default `Variation` for that flag.

Proper error handling should be implemented to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```ruby theme={null}
begin
  variations = kameleoon_client.get_variations(visitor_code)
  # only active variations
  variations = kameleoon_client.get_variations(visitor_code, only_active: true)
  # disable tracking
  variations = kameleoon_client.get_variations(visitor_code, track: false)
rescue Kameleoon::Exception::VisitorCodeInvalid
  # Handle exception
end
```

##### Parameters

| Name                                                          | Type     | Description                                                                                                       | Default |
| ------------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge>  | `String` | Unique identifier of the visitor.                                                                                 |         |
| `only_active` <Badge color="green" size="sm">optional</Badge> | `Bool`   | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `track` <Badge color="green" size="sm">optional</Badge>       | `Bool`   | An optional parameter to enable or disable tracking of the feature evaluation.                                    | `true`  |

##### Return value

| Type                      | Description                                                                                                                         |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Hash<String, Variation>` | Map that contains the assigned [`Variation`](#variation) objects of the feature flags using the keys of the corresponding features. |

##### Exceptions thrown

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### set\_forced\_variation()

The method allows you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.

When a **forced** variation is set, it overrides Kameleoon's real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `force_targeting=false` instead.

<Info>
  **Simulated** variations always take precedence in the execution order. If a **simulated** variation calculation is triggered, it will be fully processed and completed first.
</Info>

A forced variation is treated the same as an evaluated variation. It is 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 (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.

<Warning>
  It’s important to distinguish **forced** variations from **[simulated](#get_visitor_code)** variations:

  * **Forced variations**: Are specific to an individual experiment.
  * **Simulated variations**: Affect the overall **feature flag** result.
</Warning>

```ruby theme={null}
experiment_id = 9516
begin
  # Forcing the variation "on" for the experiment 9516 for the visitor
  kameleoon_client.set_forced_variation(visitor_code, experiment_id, 'on')

  # Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
  kameleoon_client.set_forced_variation(visitor_code, experiment_id, 'on', force_targeting: false)

  # Resetting the forced variation for the experiment 9516 for the visitor
  kameleoon_client.set_forced_variation(visitor_code, experiment_id, nil)
rescue Kameleoon::Exception::KameleoonError => ex
  # Handling the exception
end
```

##### Parameters

| Name                                                              | Type      | Description                                                                                                                                      | Default                                                                                                                                                                     |   |
| ----------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - |
| `visitor_code` <Badge color="red" size="sm">required</Badge>      | `String`  | Unique identifier of the visitor.                                                                                                                |                                                                                                                                                                             |   |
| `experiment_id` <Badge color="red" size="sm">required</Badge>     | `Integer` | **Experiment Id** that will be targeted and selected during the evaluation process.                                                              |                                                                                                                                                                             |   |
| `variation_key` <Badge color="red" size="sm">required</Badge>     | \`String  | NilClass\`                                                                                                                                       | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `nil`, the forced variation will be reset. |   |
| `force_targeting` <Badge color="green" size="sm">optional</Badge> | `Bool`    | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`). | `true`                                                                                                                                                                      |   |

##### Exceptions thrown

| Type                        | Description                                                                                                                                                                                                                                           |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`        | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                   |
| `FeatureExperimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `FeatureVariationNotFound`  | Exception indicating that the requested variation key(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. |

<Info>
  In most cases, only the basic error, `KameleoonError`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `StandardError`.
</Info>

#### evaluate\_audiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`evaluate_audiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated 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.

```ruby theme={null}
begin
  kameleoon_client.evaluate_audiences(visitor_code)
rescue Kameleoon::Exception::KameleoonError => ex
  # Handling the exception
end
```

##### Parameters

| Name                                                         | Type     | Description                       |
| ------------------------------------------------------------ | -------- | --------------------------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor. |

##### Exceptions thrown

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

<Info>
  In most cases, only the basic error, `KameleoonError`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `StandardError`.
</Info>

#### get\_data\_file()

<Tip>
  To evaluate all feature flags, use [`get_variations()`](#get_variations). This method is more efficient than calling `DataFile` and iterating through flags with [`get_variation()`](#get_variation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```ruby theme={null}
begin
  datafile = kameleoon_client.get_data_file
rescue StandardError => e
  # Recommended (but optional) safeguard for unexpected exceptions from third-party libraries
end
```

##### Return value

| Type       | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `DataFile` | The [`DataFile`](#datafile) containing the SDK configuration |

### Visitor data

#### get\_visitor\_code()

<Note>
  Previously called `obtain_visitor_code` - removed since SDK version `3.0.0`.
</Note>

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 our customers use their own identifiers as visitor codes should they wish, which 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, 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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/).

<Note>
  If you provide your own `visitor_code`, you must guarantee its uniqueness-the SDK cannot check it. Also, note that the length of the `visitor_code` is limited to **255** characters. Any excess characters will throw an exception.
</Note>

<Info>
  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 standard evaluation process is bypassed. Instead, the method directly returns a [`Variation`](#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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation#linking-feature-experiments-with-front-end-tracking-code), the cookie is created automatically when simulating a variant's display using the [Simulation Panel](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/validation-and-rollback/using-simulation-mode).
  * **Manually:** Set the `kameleoonSimulationFFData` cookie manually.

  It’s important to distinguish **simulated** variations from **[forced](#set_forced_variation)** variations:

  * **Simulated variations**: Affect the overall **feature flag** result.
  * **Forced variations**: Are specific to an individual experiment.

  ⚙️ **Manual setup**

  Please ensure 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 proper functionality, the cookie value must be encoded as a URI component using a method such as [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
</Info>

```ruby theme={null}
visitor_code = kameleoon_client.get_visitor_code(cookies)

visitor_code = kameleoon_client.get_visitor_code(cookies, default_visitor_code)
```

##### Parameters

| Name                   | Type   | Description                                                                                                                                                                                                        |
| ---------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| cookies                | Hash   | Cookies on the current HTTP request should be passed as a Hash object (`{:cookie_name => cookie_value}`). If you use Rails, you can pass the **cookies** variable. This field is mandatory.                        |
| default\_visitor\_code | String | This parameter will be used as the **visitor\_code** if no existing **kameleoonVisitorCode** cookie is found in the request. This field is optional, and by default, a random **visitor\_code** will be generated. |

##### Return value

| Type   | Description                                                                                                            |
| ------ | ---------------------------------------------------------------------------------------------------------------------- |
| String | A **visitor\_code** that will be associated with this particular user and should be used with most of the SDK methods. |

#### add\_data()

The `add_data()` method adds [targeting data](#data-types) 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()`](#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 by the `flush()`.

The [`track_conversion()`](#track_conversion) method also sends out any previously associated data, just like the `flush()`. The same holds true for [`get_variation()`](#get_variation) and [`get_variations()`](#get_variations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```ruby theme={null}
require "kameleoon"
require "kameleoon/data"

# Add a single data item (tracked by default)
kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))

# Add multiple data items (tracked by default)
kameleoon_client.add_data(
  visitor_code,
  Kameleoon::PageView.new("https://url.com", "title", [3]),
  Kameleoon::UserAgent("UserAgent")
)

# Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
kameleoon_client.add_data(
  visitor_code,
  Kameleoon::Data::PageView.new("https://url.com", "title", [3]),
  Kameleoon::Data::UserAgent.new("UserAgent"),
  track: false
)
```

##### Parameters

| Name                                                         | Type     | Description                                                                                                                                                                                  | Default value |
| ------------------------------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor.                                                                                                                                                            |               |
| `data` <Badge color="red" size="sm">required</Badge>         | `*Data`  | Collection of Kameleoon data types.                                                                                                                                                          |               |
| `track` <Badge color="green" size="sm">optional</Badge>      | `Bool`   | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |

##### Exceptions

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### 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 has not yet been sent when calling one of [these methods](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics), 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 our servers. 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](/developer-docs/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 parameter `is_unique_identifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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) # Interval tracking (most performant way for tracking)

kameleoon_client.flush(visitor_code, instant: true) # Instant tracking

# if you operate with unique ID
kameleoon_client.add_data(Kameleoon::UniqueIdentifier.new(true))
kameleoon_client.flush(visitor_code)
```

##### Arguments

| Name                   | Type    | Description                                                                                                                                                   |
| ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitor\_code          | String  | Unique identifier of the user. This field is mandatory.                                                                                                       |
| is\_unique\_identifier | Boolean | When `true`, the SDK links the flushed data to the visitor associated with the specified identifier.                                                          |
| instant                | Boolean | Boolean flag indicating whether the data should be sent instantly (`true`) or according to the scheduled tracking interval (`false`). This field is optional. |

#### get\_remote\_data()

<Note>
  Previously named: `retrieve_data_from_remote_source` - removed since SDK version `3.0.0`.
</Note>

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 our remote servers using our Data API. This method, along with the availability of our 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.

```ruby theme={null}
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
```

##### Parameters

| Name    | Type    | Description                                                                                                                                                                                                                                                                                |
| ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| key     | String  | The key that the data you try to retrieve is associated with. This field is mandatory.                                                                                                                                                                                                     |
| timeout | Integer | Timeout (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

| Type | Description                                                       |
| ---- | ----------------------------------------------------------------- |
| Hash | Hash object associated with retrieving data for specific **key**. |

##### Exceptions thrown

| Type  | Description                                                                                                       |
| ----- | ----------------------------------------------------------------------------------------------------------------- |
| Error | Error indicating that the request timed out or the retrieved data can't be parsed with the `JSON.parse()` method. |

#### 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 is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  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 is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).
</Warning>

<Note>
  The parameter `is_unique_identifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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 to link the extracted data with the visitor associated with the specified identifier
kameleoon_client.add_data(Kameleoon::UniqueIdentifier.new(true))
data_array = kameleoon_client.get_remote_visitor_data(visitor_code)
```

##### Parameters

| Name                                | Type                                        | Description                                                                                                                                                                                                                                                                                                                                                  |
| ----------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| visitor\_code                       | String                                      | The visitor code for which you want to retrieve the assigned data. This field is mandatory.                                                                                                                                                                                                                                                                  |
| timeout                             | Integer                                     | Timeout (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 uses the `default_timeout` value from the configuration file or 2000 milliseconds if it's not specified in the file.                                                                   |
| add\_data                           | Boolean                                     | A 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.                                                                                                                                                                                      |
| filter                              | `Kameleoon::Types::RemoteVisitorDataFilter` | Filter 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\_identifier (Deprecated) | Boolean                                     | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `false`. The field is optional.                                                                                                                                                                                                        |

##### Return value

| Type  | Description                                     |
| ----- | ----------------------------------------------- |
| Array | An array of data assigned to the given visitor. |

##### 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 is not limited to goal data. You can use parameters within the `get_remote_visitor_data()` method to retrieve data on a variety of visitor behaviors.

<Note>
  Here is the list of available `Kameleoon::Types::RemoteVisitorDataFilter` options:

  | Name                                                                    | Type      | Description                                                                                                                                                                                                                                                                                                                                     | Default |
  | ----------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | previous\_visit\_amount <Badge color="green" size="sm">optional</Badge> | `Integer` | Number of previous visits to retrieve data from. Number between `1` and `25`                                                                                                                                                                                                                                                                    | `1`     |
  | current\_visit <Badge color="green" size="sm">optional</Badge>          | `Boolean` | If true, current visit data will be retrieved                                                                                                                                                                                                                                                                                                   | `true`  |
  | custom\_data <Badge color="green" size="sm">optional</Badge>            | `Boolean` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                         | `true`  |
  | page\_views <Badge color="green" size="sm">optional</Badge>             | `Boolean` | If true, page data will be retrieved.                                                                                                                                                                                                                                                                                                           | `false` |
  | geolocation <Badge color="green" size="sm">optional</Badge>             | `Boolean` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                    | `false` |
  | device <Badge color="green" size="sm">optional</Badge>                  | `Boolean` | If true, device data will be retrieved.                                                                                                                                                                                                                                                                                                         | `false` |
  | browser <Badge color="green" size="sm">optional</Badge>                 | `Boolean` | If true, browser data will be retrieved.                                                                                                                                                                                                                                                                                                        | `false` |
  | operating\_system <Badge color="green" size="sm">optional</Badge>       | `Boolean` | If true, operating system data will be retrieved.                                                                                                                                                                                                                                                                                               | `false` |
  | conversions <Badge color="green" size="sm">optional</Badge>             | `Boolean` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | experiments <Badge color="green" size="sm">optional</Badge>             | `Boolean` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | kcs <Badge color="green" size="sm">optional</Badge>                     | `Boolean` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/assets/segments/target-users-based-on-likelihood-to-convert)                                                                                                                                                            | `false` |
  | visitor\_code <Badge color="green" size="sm">optional</Badge>           | `Boolean` | If true, Kameleoon will retrieve the `visitorCode` from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their `visitorCode`, always receives the same variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | personalization <Badge color="green" size="sm">optional</Badge>         | `Boolean` | If true, personalization data will be retrieved. This is required for the personalization condition.                                                                                                                                                                                                                                            | `false` |
  | cbs <Badge color="green" size="sm">optional</Badge>                     | `Boolean` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                        | `false` |
</Note>

#### 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](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) 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.

```ruby theme={null}
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
```

##### Parameters

| Name                | Type    | Description                                                                                                                                                                            |
| ------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitor\_code       | String  | A unique visitor identification string, can't exceed 255 characters length.                                                                                                            |
| custom\_data\_index | Integer | An integer representing the index of the custom data you want to use to target your BigQuery Audiences.                                                                                |
| warehouse\_key      | String  | A unique key to identify the warehouse data (usually your internal user ID). This field is optional.                                                                                   |
| timeout             | Integer | Timeout (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

| Type                    | Description                                                                     |
| ----------------------- | ------------------------------------------------------------------------------- |
| `Kameleoon::CustomData` | A `CustomData` instance confirming that the data has been added to the visitor. |

##### Exceptions thrown

| Type                                     | Description                                                                                                        |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Kameleoon::Exception::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid (it is either empty or longer than 255 characters). |
| StandardError                            | Exception indicating that the request timed out or any other reason of failure.                                    |

#### set\_legal\_consent()

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](/user-manual/project-management/consent-management-policy).

```ruby theme={null}
visitor_code = kameleoon_client.get_visitor_code(cookies)
kameleoon_client.set_legal_consent(visitor_code, true, cookies)
```

##### Parameters

| Name          | Type   | Description                                                                                                                                                                                                         |
| ------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitor\_code | String | The user's unique identifier. This field is required.                                                                                                                                                               |
| consent       | Bool   | A boolean value representing the legal consent status. `true` indicates the visitor has given legal consent; `false` indicates the visitor never provided, or has withdrawn, legal consent. This field is required. |
| cookies       | Hash   | The HTTP response where values in the cookies will be adjusted based on the legal consent status. This field is optional.                                                                                           |

##### Exceptions thrown

| Type                                     | Description                                                                                                       |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Kameleoon::Exception::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid. It is either empty or longer than 255 characters. |

##### Consent revocation behavior

When you call `set_legal_consent()` with `consent=false`, the SDK does not 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 will not 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](/user-manual/assets/goals/create-a-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 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.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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::Conversion.new(32, 10, false))
kameleoon_client.track_conversion(visitor_code, goal_id)

# Add metadata
cd = Kameleoon::CustomData.new(1, "metadata");
kameleoon_client.track_conversion(visitorCode, goalId, metadata: [cd])
```

##### Parameters

| Name                                                         | Type                | Description                                                                                                                                                                                                                                                                                                                          | Default |
| ------------------------------------------------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `String`            | Unique identifier of the visitor.                                                                                                                                                                                                                                                                                                    |         |
| `goal_id` <Badge color="red" size="sm">required</Badge>      | `Integer`           | ID of the goal.                                                                                                                                                                                                                                                                                                                      |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>    | `Float`             | Revenue of the conversion.                                                                                                                                                                                                                                                                                                           | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge>   | `Bool`              | Defines if the revenue is positive or negative.                                                                                                                                                                                                                                                                                      | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge>   | `Array<CustomData>` | Lets you set specific values for custom data which have been defined as metadata for the goal in the Kameleoon App. Example: `[CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]`. In this example, `5` and `6` are the indexes of the custom data (5 = “Payment Type”, 6 = “Delivery Method”). | `nil`   |
| `isUniqueIdentifier` *(deprecated)*                          | `Bool`              | An optional parameter for specifying if the visitor\_code is a unique identifier.                                                                                                                                                                                                                                                    | `false` |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  If the `metadata` parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the [`add_data()`](#add_data) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#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').

  ```ruby theme={null}
  kameleoon_client.add_data(visitor_code, Kameleoon::CustomData.new(5, "Credit Card"), Kameleoon::CustomData.new(9, "Express Delivery"))
  kameleoon_client.track_conversion(visitor_code, 10, metadata: [Kameleoon::CustomData.new(5, "Amex Credit Card")])
  ```
</Note>

##### Exceptions

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### 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 five 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](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) for more information on implementing this method.

```ruby theme={null}
engine_tracking_code = kameleoon_client.get_engine_tracking_code(visitor_code)
```

<Note>
  * To use this feature, implement both the Ruby SDK and Kameleoon [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation). Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing `</body>` tag.
  * If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the [JavaScript / TypeScript SDK](/developer-docs/sdks/web-sdks/js-sdk). This option works well for [serverless edge compute platforms](/developer-docs/feature-experimentation/implementation-and-deployment/serverless-edge-compute-starter-kits). The JavaScript / TypeScript SDK automatically tracks variations when you call [`getVisitorCode`](/developer-docs/sdks/web-sdks/js-sdk#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.

  ```html theme={null}
  <html lang="en">
    <body>
      <script>
        const engineTrackingCode = `
          window.kameleoonQueue = window.kameleoonQueue || [];
          window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
          window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
        `;
        const script = document.createElement('script');

        script.textContent = engineTrackingCode;
        document.body.appendChild(script);
      </script>

    </body>
  </html>
  ```

  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.
</Note>

##### Parameters

| Name                                                         | Type     | Description                       |
| ------------------------------------------------------------ | -------- | --------------------------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor. |

##### Return value

| Type     | Description                              |
| -------- | ---------------------------------------- |
| `String` | JavaScript code to insert into the page. |

### Events

#### 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.

```ruby theme={null}

kameleoon_client.on_update_configuration(
  # configuration was updated
)
```

##### Parameters

| Name      | Type       | Description                                                                                              |
| --------- | ---------- | -------------------------------------------------------------------------------------------------------- |
| `handler` | `Callable` | The handler that will be called when the configuration is updated using a real-time configuration event. |

### Data types

#### Browser

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

| Name                                                         | Type          | Description                                                                                     |
| ------------------------------------------------------------ | ------------- | ----------------------------------------------------------------------------------------------- |
| `browser_type` <Badge color="red" size="sm">required</Badge> | `BrowserType` | List of browsers: `CHROME`, `INTERNET_EXPLORER`, `FIREFOX`, `SAFARI`, `OPERA`, `OTHER`.         |
| `version` <Badge color="green" size="sm">optional</Badge>    | `Float`       | Version of the browser, floating point number represents major and minor version of the browser |

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::CHROME))

kameleoon_client.add_data(visitor_code, Kameleoon::Browser.new(Kameleoon::BrowserType::SAFARI, 10.0))
```

#### PageView

| Name      | Type   | Description                                        |
| --------- | ------ | -------------------------------------------------- |
| url       | String | URL of the page viewed. This field is mandatory.   |
| title     | String | Title of the page viewed. This field is mandatory. |
| referrers | Array  | Referrers of viewed pages. This field is optional. |

<Note>
  The referrer's index (ID) is available in the Acquisition channel configuration page of our Back-Office. Be careful: this index starts at 0, so the first [acquisition channel](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) you create for a site would have the ID 0, not 1.
</Note>

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::PageView.new("https://url.com", "title", [3]))
```

#### Conversion

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

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goal_id` in the Kameleoon app.
</Tip>

| Name                                                       | Type                | Description                                     | Default |
| ---------------------------------------------------------- | ------------------- | ----------------------------------------------- | ------- |
| `goal_id` <Badge color="red" size="sm">required</Badge>    | `Integer`           | ID of the goal.                                 |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `Float`             | Revenue of the conversion                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `Bool`              | Defines if the revenue is positive or negative. | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `Array<CustomData>` | Metadata of the conversion.                     | `nil`   |

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(32, 10))

kameleoon_client.add_data(visitor_code, Kameleoon::Conversion.new(33, 0, true))

kameleoon_client.add_data(
  visitor_code,
  Kameleoon::Conversion.new(34, metadata: [
    Kameleoon::CustomData.new(3, 'metadata1', 'md2'),
    Kameleoon::CustomData.new(5, 'md3'),
  ])
)
```

#### 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](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports.

To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Name                                                      | Type               | Description                                                                                                                                                                             | Default |
| --------------------------------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| index/name <Badge color="red" size="sm">required</Badge>  | `Integer`/`String` | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |         |
| values <Badge color="red" size="sm">required</Badge>      | `Array`            | Values of the custom data to be stored.                                                                                                                                                 |         |
| overwrite <Badge color="green" size="sm">optional</Badge> | `Boolean`          | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true`  |

<Note>
  * 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](/user-manual/assets/custom-data/manage-custom-data) 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 is not up to date or the name is not registered, will result in the data being ignored.
</Note>

```ruby theme={null}
custom_data = Kameleoon::CustomData.new(1, 'value')

# With several values
custom_data = Kameleoon::CustomData.new(1, 'value1', 'value2')

# To set the 'overwrite' flag to false
custom_data = Kameleoon::CustomData.new(1, 'value', overwrite: false)

# To use a name instead of the index
custom_data = Kameleoon::CustomData.new('my-custom-data', 'value')

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

# From hash with the 'overwrite' flag set to false
custom_data = Kameleoon::CustomData.new({ 'id' => 1, 'values' => ['value'], 'overwrite' => false })

# From hash with a name instead of the index
custom_data = Kameleoon::CustomData.new({ 'name' => 'my-custom-data', 'values' => ['value'] })

kameleoon_client.add_data(visitor_code, custom_data)
```

#### Device

| Name   | Type       | Description                                                                   |
| ------ | ---------- | ----------------------------------------------------------------------------- |
| device | DeviceType | List of devices: **PHONE**, **TABLET**, **DESKTOP**. This field is mandatory. |

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::Device.new(Kameleoon::DeviceType::DESKTOP))
```

#### 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](/user-manual/faq#how-does-kameleoon-filter-bot-traffic-from-my-results).

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

| Name  | Type   | Description                                                                             |
| ----- | ------ | --------------------------------------------------------------------------------------- |
| value | String | The User-Agent value that will be sent with tracking requests. This field is mandatory. |

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::UserAgent.new("Your User Agent"))
```

#### 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](/developer-docs/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 is connected to the anonymous visitor using session merging capabilities.

| Name  | Type    | Description                                                                                   |
| ----- | ------- | --------------------------------------------------------------------------------------------- |
| value | Boolean | Parameter for specifying if the visitor\_code is a unique identifier. This field is required. |

```ruby theme={null}
kameleoon_client.add_data(visitorCode, Kameleoon::UniqueIdentifier.new(true))
```

#### OperatingSystem

`OperatingSystem` contains information about the visitor's operating system.

<Note>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first.
</Note>

| Name | Type                | Description                                                                                                        |
| ---- | ------------------- | ------------------------------------------------------------------------------------------------------------------ |
| type | OperatingSystemType | List of types: **WINDOWS**, **MAC**, **IOS**, **LINUX**, **ANDROID**, **WINDOWS\_PHONE**. This field is mandatory. |

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::OperatingSystem.new(Kameleoon::OperatingSystemType::ANDROID))
```

#### Cookie

`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.
</Note>

| Name    | Type | Description                                                                                                   |
| ------- | ---- | ------------------------------------------------------------------------------------------------------------- |
| cookies | Hash | Hash object (`{:cookie_name => cookie_value}`) consisting of cookie keys and values. This field is mandatory. |

```ruby theme={null}
cookie = Kameleoon::Cookie.new({ "k1" => "v1", "k2" => "v2" })
kameleoon_client.add_data(visitor_code, cookie)
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Name                                                          | Type                  | Description                                                                                                      |
| ------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>       | `String`              | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>      | <nobr>`String`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>        | <nobr>`String`</nobr> | The city of the visitor.                                                                                         |
| `postal_code` <Badge color="green" size="sm">optional</Badge> | <nobr>`String`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>    | `Float`               | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>   | `Float`               | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```ruby theme={null}
kameleoon_client.add_data(visitor_code, Kameleoon::Geolocation.new("France", "Île-de-France", "Paris"))
```

#### ApplicationVersion

`ApplicationVersion` represents the semantic version number of your application.

<Tip>
  A **visitor** can have only one `ApplicationVersion`. Adding a second instance will overwrite the first one.
</Tip>

| Name                                                    | Type     | Description                                                                                                                                      |
| ------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| version <Badge color="green" size="sm">optional</Badge> | `String` | The mobile application version. This field must follow semantic versioning. Accepted formats are `major`, `major.minor`, or `major.minor.patch`. |

```ruby theme={null}
kameleoon_client_sdk.add_data(visitorCode, Kameleoon::ApplicationVersion.new("10")) # major

kameleoon_client_sdk.add_data(visitorCode, Kameleoon::ApplicationVersion.new("10.20")) # major.minor

kameleoon_client_sdk.add_data(visitorCode, Kameleoon::ApplicationVersion.new("10.20.30")) # major.minor.patch
```

### 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, please contact your Customer Success Manager.

| Name            | Type                        | Description                                                                       |
| --------------- | --------------------------- | --------------------------------------------------------------------------------- |
| `feature_flags` | `Hash<String, FeatureFlag>` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `date_modified` | `Integer`                   | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```ruby theme={null}
# Retrieves the hash of feature flags from the DataFile.
# The hash is keyed by feature flag identifiers, with each value being a FeatureFlag object.
feature_flags = datafile.feature_flags

# Retrieves the last modification timestamp of the DataFile.
# The value is an Integer representing milliseconds since the Unix epoch.
date_modified = datafile.date_modified
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), environment status, and other related details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name                    | Type                      | Description                                                                |
| ----------------------- | ------------------------- | -------------------------------------------------------------------------- |
| `environment_enabled`   | `Bool`                    | Indicating whether the feature flag is enabled in the current environment. |
| `default_variation_key` | `String`                  | The key of the default variation associated with the feature flag.         |
| `variations`            | `Hash<String, Variation>` | A map of `Variation` objects, keyed by variation keys.                     |
| `rules`                 | `Array<Rule>`             | A list of `Rule` objects                                                   |

```ruby theme={null}
# Check whether the feature flag is enabled in the current environment
is_environment_enabled = feature_flag.environment_enabled

# Retrieve the key of the default variation
default_variation_key = feature_flag.default_variation_key

# Retrieve the default variation object
default_variation = feature_flag.default_variation

# Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
variations = feature_flag.variations

# Retrieve all targeting rules associated with the feature flag
rules = feature_flag.rules
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                      | Description                                            |
| ------------ | ------------------------- | ------------------------------------------------------ |
| `variations` | `Hash<String, Variation>` | A map of `Variation` objects, keyed by variation keys. |

```ruby theme={null}
# Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
variations = rule.variations
```

#### Variation

`Variation` contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).

| Name           | Type                     | Description                                                                                                                             |
| -------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| name           | `String`                 | The name of the variation.                                                                                                              |
| key            | `String`                 | The unique key identifying the variation.                                                                                               |
| id             | `Integer` or `NilClass`  | The ID of the assigned variation (or `nil` if it's the default variation).                                                              |
| experiment\_id | `Integer` or `NilClass`  | The ID of the experiment associated with the variation (or `nil` if default).                                                           |
| variables      | `Hash<String, Variable>` | A hash containing the variables of the assigned variation, keyed by variable names. This could be empty if no variables are associated. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#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.
</Note>

```ruby theme={null}
# Retrieving the variation name
variation_name = variation.name

# Retrieving the variation key
variation_key = variation.key

# Retrieving the variation id
variation_id = variation.id

# Retrieving the experiment id
experiment_id = variation.experiment_id

# Retrieving the variables map
variables = variation.variables
```

#### Variable

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

| Name  | Type     | Description                                                                                                                           |
| ----- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| key   | `String` | The unique key identifying the variable.                                                                                              |
| type  | `String` | The type of the variable. Possible values: **BOOLEAN**, **NUMBER**, **STRING**, **JSON**, **JS**, **CSS**                             |
| value | `Object` | The value of the variable, which can be of the following types: **Boolean**, **Integer**, **Float**, **String**, **Hash**, **Array**. |

```ruby theme={null}
# Retrieving the variables map
variables = variation.variables

# Variable type can be retrieved for further processing
type = variables["isDiscount"].type

# Retrieving the variable value by key
is_discount = variables["isDiscount"].value

# Variable value can be of different types (e.g., String)
title = variables["title"].value
```

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `4.0.0`.
</Warning>

#### get\_feature\_variation\_key()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`get_variation()`](#get_variation) instead.
</Note>

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 does not match any of the rules, the default value will be returned, which we can define in your customer's 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](/developer-docs/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 parameter `is_unique_identifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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)
	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 in the experiment, but should see the reference variation.
rescue Kameleoon::Exception::VisitorCodeInvalid
	# The visitor code 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
```

##### Parameters

| Name                                | Type    | Description                                                                                          |
| ----------------------------------- | ------- | ---------------------------------------------------------------------------------------------------- |
| visitor\_code                       | string  | Unique identifier of the user. This field is mandatory.                                              |
| feature\_key                        | string  | Key of the feature you want to expose to a user. This field is mandatory.                            |
| is\_unique\_identifier (Deprecated) | Boolean | When `true`, the SDK links the flushed data to the visitor associated with the specified identifier. |

##### Return value

| Type   | Description                                                                         |
| ------ | ----------------------------------------------------------------------------------- |
| string | Variation key of the feature flag that is registered for a given **visitor\_code**. |

##### Exceptions thrown

| Type                                             | Description                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Kameleoon::Exception::FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the SDK''s internal configuration. This exception 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::FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                       |
| Kameleoon::Exception::VisitorCodeInvalid         | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters).                                                                                                                                                                                                             |

#### get\_active\_feature\_list\_for\_visitor()

<Note>
  Use [`get_active_features()`](#get_active_features) instead.
</Note>

This method only takes `visitorCode` as an input parameter. The result only contains active feature flags for a given visitor.

```ruby theme={null}
active_feature_flag_list = kameleoon_client.get_active_feature_list_for_visitor(visitor_code)
```

##### Arguments

| Name          | Type   | Description                                             |
| ------------- | ------ | ------------------------------------------------------- |
| visitor\_code | String | Unique identifier of the user. This field is mandatory. |

##### Return value

| Type  | Description                                                              |
| ----- | ------------------------------------------------------------------------ |
| Array | List of feature flag keys which are active for a given **visitor\_code** |

##### Exceptions thrown

| Type                                     | Description                                                                                            |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Kameleoon::Exception::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters). |

#### get\_active\_features()

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

<Note>
  This method is deprecated and will be removed in SDK version `4.0.0`. Use [`get_variations()`](#get_variations) instead.
</Note>

```ruby theme={null}
active_features = kameleoon_client.get_active_features(visitor_code)
```

##### Arguments

| Name          | Type     | Description                                             |
| ------------- | -------- | ------------------------------------------------------- |
| visitor\_code | `String` | Unique identifier of the user. This field is mandatory. |

##### Return value

| Type                      | Description                                                                                               |
| ------------------------- | --------------------------------------------------------------------------------------------------------- |
| `Hash<String, Variation>` | A hash that contains the assigned variations of the active features using the active feature IDs as keys. |

##### Exceptions thrown

| Type                                     | Description                                                                                            |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Kameleoon::Exception::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters). |

#### get\_feature\_variable()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`get_variation()`](#get_variation) instead.
</Note>

<Note>
  Previously called `obtain_feature_variable` - deprecated since SDK version `2.1.0` and will be removed in a future releases.
</Note>

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 does not 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](/developer-docs/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 parameter `is_unique_identifier` is deprecated. Please use [`UniqueIdentifier`](#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 is connected to the anonymous visitor using session merging capabilities.
</Note>

```ruby theme={null}
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)
	# 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 in the experiment, but should see the reference variation.
rescue Kameleoon::Exception::FeatureVariableNotFound
	# Requested variable not defined in Kameleoon
rescue Kameleoon::Exception::FeatureEnvironmentDisabled
	# The feature is disabled for the environment.
rescue Kameleoon::Exception::VisitorCodeInvalid
	# The visitor code you passed to the method isn't valid and can't be accepted by SDK.
end
```

##### Parameters

| Name                                | Type    | Description                                                                                           |
| ----------------------------------- | ------- | ----------------------------------------------------------------------------------------------------- |
| visitor\_code                       | string  | Unique identifier of the user. This field is mandatory.                                               |
| feature\_key                        | string  | Key of the feature you want to expose to a user. This field is mandatory.                             |
| variable\_name                      | string  | Name of the variable for which you want to get the value. This field is mandatory.                    |
| is\_unique\_identifier (Deprecated) | Boolean | When `true`, the SDK links the flushed data with to visitor associated with the specified identifier. |

##### Return value

| Type | Description                                                                                                                                           |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| any  | Value of a variation's variable that is registered for a given **visitor\_code** for this feature flag. Possible types: boolean, number, string, hash |

##### Exceptions thrown

| Type                                             | Description                                                                                                                                                                                                                                                                                                       |
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Kameleoon::Exception::FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception 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::FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled in the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                       |
| Kameleoon::Exception::VisitorCodeInvalid         | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters).                                                                                                                                                                                                            |
| Kameleoon::Exception::FeatureVariableNotFound    | Exception indicating that the requested variable has not been found. Check that the variable's key matches the key in your code.                                                                                                                                                                                  |

#### get\_feature\_variation\_variables()

<Note>
  Use [`get_variation()`](#get_variation) instead.
</Note>

To retrieve the all feature variables, call the `get_feature_variation_variables` method. A feature variable can be changed using 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. It throws an error (`FeatureNotFound`) if the requested feature flag has not been found in the SDK's client configuration. If the variation key isn't found, the method throws (`FeatureVariationNotFound`) error.

```ruby theme={null}
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 activated in Kameleoon
rescue Kameleoon::Exception::FeatureVariationNotFound
	# Requested variation not defined in Kameleoon
rescue Kameleoon::Exception::FeatureEnvironmentDisabled
	# The feature is disabled for the environment.
end
```

##### Parameters

| Name           | Type   | Description                                                          |
| -------------- | ------ | -------------------------------------------------------------------- |
| feature\_key   | string | Key of the feature flag you want to obtain. This field is mandatory. |
| variation\_key | string | Key of the variation you want to obtain. This field is mandatory.    |

##### Return value

| Type | Description                                                                                                                                                     |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Hash | Data associated with this feature flag and variation. The values can be a String, Boolean, Number or Hash (depending on the type defined in the web interface). |

##### Exceptions thrown

| Type                                             | Description                                                                                                                                                                                                                                                                                                       |
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Kameleoon::Exception::FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This exception 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::FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                      |
| Kameleoon::Exception::FeatureVariationNotFound   | Exception indicating that the requested variation ID has not been found in the SDK's internal configuration. This exception is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side.                                                             |

#### get\_feature\_list()

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

```ruby theme={null}
feature_list = kameleoon_client.get_feature_list
```

##### Return value

| Type    | Description               |
| ------- | ------------------------- |
| `Array` | List of feature flag keys |
