Con el SDK de Ruby de Kameleoon, puede ejecutar experimentos y activar feature flags en su servidor Ruby de back-end. Es sencillo integrar nuestro SDK en su aplicación web y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Última versión del SDK de Ruby: 3.18.0 Changelog.
Métodos del SDK: Para la documentación de referencia completa del SDK de Ruby, consulte la sección referencia.
Guía del desarrollador
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:
gem install kameleoon-client-ruby
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. 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:
| Clave | Descripción | Valor predeterminado |
|---|
client_id (obligatorio) | Required for authentication to the Kameleoon service. To find your client id, see the API credentials documentation. | |
client_secret (obligatorio) | Required for authentication to the Kameleoon service. To find your client secret, see the API credentials documentation. | |
session_duration_minute (opcional) | Designa el intervalo de tiempo predefinido durante el cual Kameleoon almacena al visitante y sus datos asociados en memoria (RAM). Tenga en cuenta que aumentar la duración de la sesión incrementa la cantidad de RAM que debe asignarse para almacenar los datos del visitante. | 30 minutos |
refresh_interval_minute (opcional) | Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos activos y los feature flags. El valor determina el tiempo máximo necesario para propagar los cambios, como activar o desactivar feature flags o lanzar experimentos, a sus servidores de producción. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicar las nuevas configuraciones en tiempo real, sin ningún retraso. | 60 minutos |
default_timeout_millisecond (opcional) | Especifica el tiempo de espera, en milisegundos, para las solicitudes de red desde el SDK. Establezca el valor en 30 segundos o más si no dispone de una conexión estable. Algunos métodos tienen un parámetro adicional que puede utilizar para anular el tiempo de espera predeterminado para ese método en particular. Si no especifica el tiempo de espera para un método de forma explícita, el SDK utiliza este valor predeterminado. | 10000 milisegundos |
tracking_interval_millisecond (opcional) | Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que Kameleoon haya evaluado para cualquier feature flag o cuyos datos se hayan vaciado se incluyen en esta solicitud de seguimiento, que el SDK realiza una vez por intervalo. El valor mínimo es 1000 ms, que también es el predeterminado, y el valor máximo es 5000 ms. | 1000 milisegundos |
environment (opcional) | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles. | production |
top_level_domain (obligatorio en modo híbrido) | El dominio de nivel superior actual de su sitio web. Use el formato: example.com. No incluya https://, www ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior. | nil |
network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | 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 instead. | nil |
The Kameleoon Ruby SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.
Initialize the client
After you’ve installed the SDK into your application and configured the correct credentials (in /etc/kameleoon/client-ruby.yaml or Kameleoon::KameleoonClientConfig), you must set up a server-side experiment in the Kameleoon App.
El siguiente paso es crear el cliente Kameleoon en el código de su aplicación. El siguiente código proporciona un ejemplo de creación del cliente Kameleoon. Un Kameleoon::KameleoonClient es un objeto singleton que actúa como puente entre su aplicación y Kameleoon. Incluye todos los métodos y propiedades que necesita para ejecutar un experimento.
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.
# 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)
Si utiliza Ruby on Rails, le recomendamos inicializar el cliente Kameleoon al arrancar el servidor en el archivo application.rb.
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
A continuación, puede acceder al cliente Kameleoon en sus controladores:
class YourController < ApplicationController
def index
kameleoon_client = App::Application.config.kameleoon_client
# Your controller code, using the kameleoon_client
end
end
Activación de un feature flag
Asignación de un ID único a un usuario
To assign a unique ID to a user, you can use the get_visitor_code() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a default_visitor_code that you would have generated. The ID is then set in a response headers cookie.
Si está usando Kameleoon en modo híbrido, llamar al método get_visitor_code() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.
To determine the status or variation of a feature flag for a specific user, you should use the get_variation() or feature_active?() method to retrieve the configuration based on the feature_key.
El método get_variation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del feature_key y el visitor_code.
El método feature_active?() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
If your feature flag has associated variables (such as specific behaviors tied to each variation) get_variation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the 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. De forma predeterminada, 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. Si desea saber más sobre how tracking works, view this article
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the add_data() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the get_remote_visitor_data() method. This method asynchronously fetches data from the servers. It 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.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato UserAgent.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método track_conversion() y proporcione los parámetros requeridos visitor_code y goal_id.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=true.
Envío de eventos a soluciones de analítica
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the get_engine_tracking_code() method.
El método get_engine_tracking_code() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.
Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:
Mismo ID de usuario en todos los dispositivos
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.
Instancias multi-servidor con IDs consistentes
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with get_remote_visitor_data()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the get_remote_visitor_data() method description for further guidance. In the below code, it 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.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
# 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)
# 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.
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
After cross-device reconciliation is enabled, calling get_remote_visitor_data() with the parameter userId retrieves all known data for a given user.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
get_remote_visitor_data() with added UniqueIdentifier(true) - to retrieve data for all linked visitors.
track_conversion() or flush() with added UniqueIdentifier(true) data - to track some data for specific visitor that is associated with another visitor.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
# 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)
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método get_visitor_code(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, 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.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitor_code predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
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() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
- 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.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:
- La clave debe ser un
String.
- Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único).
- La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios.
También puede utilizar sus propios datos externos para segmentar a los usuarios.
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.
Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.
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
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
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
Referencia
This is a full reference documentation of the Ruby SDK.
Inicialización
create()
El punto de partida para utilizar el SDK es el paso de inicialización. Todas las interacciones con el SDK se realizan a través de un objeto llamado Kameleoon::KameleoonClient, por lo que necesita crear este objeto.
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')
Argumentos
| Name | Type | Description |
|---|
| site_code | String | Es la clave única del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| configuration_file_path | String | Ruta al archivo de configuración del SDK. This field is optional, and set to /etc/kameleoon/client-ruby.yaml by default. |
| config | Kameleoon::KameleoonClientConfig | Objeto de configuración del SDK que puede pasar en lugar de utilizar un archivo de configuración. Este campo es opcional. |
Excepciones lanzadas
| 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.
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
Valor de retorno
| Tipo | Descripción |
|---|
Boolean | true if the Kameleoon client instance was successfully initialized, otherwise false. |
Feature flags y variaciones
feature_active?()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Previously called activate_feature - removed since SDK version 3.0.0.
Este método toma un 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.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
Si especifica un visitor_code, el método feature_active? usa el visitor_code como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitor_code y establece el parámetro is_unique_identifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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
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.
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | String | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | 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). |
Valor de retorno
| Type | Description |
|---|
Boolean | Value of the feature that is registered for a given visitor_code. |
Excepciones lanzadas
| 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()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera la Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitor_code and feature_key as mandatory arguments. The track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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
Argumentos
| Name | Type | Description | Default |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. | |
| feature_key (obligatorio) | String | Clave de la funcionalidad que desea exponer a un visitante. | |
| track (opcional) | Bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureNotFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
get_variations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. 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.
- El parámetro
track controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to true. Si se establece en false, el seguimiento estará deshabilitado.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
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
Argumentos
| Name | Type | Description | Default |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. | |
| only_active (opcional) | Bool | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false). | false |
| track (opcional) | Bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Hash<String, Variation> | Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
set_forced_variation()
El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set force_targeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
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.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
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
Argumentos
| Name | Type | Description | Default | |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. | | |
| experiment_id (obligatorio) | Integer | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | | |
| variation_key (obligatorio) | `String | NilClass` | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. If the value is nil, the forced variation will be reset. | |
| force_targeting (opcional) | Bool | Indica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false). | true | |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureExperimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
FeatureVariationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
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.
evaluate_audiences()
- 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.
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. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
begin
kameleoon_client.evaluate_audiences(visitor_code)
rescue Kameleoon::Exception::KameleoonError => ex
# Handling the exception
end
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
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.
get_data_file()
Devuelve la configuración actual del SDK como un objeto DataFile.
begin
datafile = kameleoon_client.get_data_file
rescue StandardError => e
# Recommended (but optional) safeguard for unexpected exceptions from third-party libraries
end
Valor de retorno
| Tipo | Descripción |
|---|
DataFile | El DataFile que contiene la configuración del SDK |
Datos del visitante
get_visitor_code()
Previously called obtain_visitor_code - removed since SDK version 3.0.0.
Llame al método auxiliar get_visitor_code para obtener el visitor_code de Kameleoon del visitante actual. Este método es importante al utilizar Kameleoon en un entorno mixto de front-end y back-end, donde se debe garantizar la precisión en la identificación del usuario. La lógica de implementación es la siguiente:
- Check for a kameleoonVisitorCode cookie or query parameter associated with the current Solicitud HTTP. If found, use this as the visitor identifier.
- 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.
- If no cookie, paramater, or argument is found, randomly generate a unique identifier.
In all cases, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. In later visits, the identifier that you set is the the value returned by the method.
Para más información, consulte este artículo.
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.
The get_visitor_code() method allows you to set simulated variations for a visitor. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:
- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manualmente: Establezca la cookie
kameleoonSimulationFFData manualmente.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
⚙️ Manual setupAsegúrese de que la cookie kameleoonSimulationFFData siga este formato:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación con varId del experimento expId para el featureKey indicado.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para el featureKey indicado.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as encodeURIComponent.
visitor_code = kameleoon_client.get_visitor_code(cookies)
visitor_code = kameleoon_client.get_visitor_code(cookies, default_visitor_code)
Argumentos
| 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. Este campo es obligatorio. |
| 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. |
Valor de retorno
| 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()
El método add_data() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método add_data() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método track_conversion() también envía cualquier dato previamente asociado, al igual que flush(). Lo mismo aplica para los métodos get_variation() y get_variations() si se desencadena una regla de experimentación.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
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
)
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. | |
| data (obligatorio) | *Data | Colección de tipos de datos de Kameleoon. | |
| track (opcional) | Bool | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | true |
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
flush()
- 📨 Envía datos de seguimiento a 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, 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.
Si especifica un visitor_code, el método flush() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitor_code y establece el parámetro is_unique_identifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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)
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
| 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). Este campo es opcional. |
get_remote_data()
Previously named: retrieve_data_from_remote_source - removed since SDK version 3.0.0.
The get_remote_data() method lets you retrieve data (according to a key passed as argument) for a specified siteCode (specified in Kameleoon::KameleoonClientFactory.create()) stored on a remote Kameleoon server. Usually, data is stored on 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.
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
Argumentos
| Name | Type | Description |
|---|
| key | String | The key that the data you try to retrieve is associated with. Este campo es obligatorio. |
| 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. |
Valor de retorno
| Type | Description |
|---|
| Hash | Hash object associated with retrieving data for specific key. |
Excepciones lanzadas
| 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.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- 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 for a better understanding of possible use cases.
De forma predeterminada, 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.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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)
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| 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 | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es true. Este campo es opcional. |
| filter | Kameleoon::Types::RemoteVisitorDataFilter | Filter that specifies which data should be retrieved from visits. De forma predeterminada, 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. Este campo es opcional. |
| is_unique_identifier (Obsoleto) | Boolean | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es false. The field is optional. |
Valor de retorno
| Type | Description |
|---|
| Array | An array of data assigned to the given visitor. |
Using parameters in get_remote_visitor_data()
El método get_remote_visitor_data() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos del visitante. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, 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.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método get_remote_visitor_data() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available Kameleoon::Types::RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| previous_visit_amount (opcional) | Integer | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| current_visit (opcional) | Boolean | If true, current visit data will be retrieved | true |
| custom_data (opcional) | Boolean | If true, custom data will be retrieved. | true |
| page_views (opcional) | Boolean | If true, page data will be retrieved. | false |
| geolocation (opcional) | Boolean | If true, geolocation data will be retrieved. | false |
| device (opcional) | Boolean | If true, device data will be retrieved. | false |
| browser (opcional) | Boolean | If true, browser data will be retrieved. | false |
| operating_system (opcional) | Boolean | If true, operating system data will be retrieved. | false |
| conversions (opcional) | Boolean | If true, conversion data will be retrieved. | false |
| experiments (opcional) | Boolean | If true, experiment data will be retrieved. | false |
| kcs (opcional) | Boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitor_code (opcional) | 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. | true |
| personalization (opcional) | Boolean | If true, personalization data will be retrieved. This is required for the personalization condition. | false |
| cbs (opcional) | Boolean | If true, Contextual Bandit score data will be retrieved. | false |
get_visitor_warehouse_audience()
Retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
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
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | A unique visitor identification string, can’t exceed 255 characters length. |
| custom_data_index | Integer | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. |
| warehouse_key | String | A unique key to identify the warehouse data (usually your internal user ID). Este campo es opcional. |
| timeout | Integer | Timeout (in milliseconds). This parameter specifies the maximum amount of time to wait for a result. Este campo es opcional. If not provided, el valor predeterminado es 10000 milliseconds. |
Valor de retorno
| Type | Description |
|---|
Kameleoon::CustomData | A CustomData instance confirming that the data has been added to the visitor. |
Excepciones lanzadas
| 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.
visitor_code = kameleoon_client.get_visitor_code(cookies)
kameleoon_client.set_legal_consent(visitor_code, true, cookies)
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
| consent | Bool | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent; false indicates the visitor never provided, or has withdrawn, legal consent. Este campo es obligatorio. |
| cookies | Hash | The HTTP response where values in the cookies will be adjusted based on the legal consent status. Este campo es opcional. |
Excepciones lanzadas
| Type | Description |
|---|
| Kameleoon::Exception::VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. Está vacío o tiene más de 255 caracteres. |
Comportamiento al revocar el consentimiento
Cuando llama a set_legal_consent() con consent=false, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.
Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.
Objetivos y analítica de terceros
track_conversion()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para track a conversion for a specific goal and user. This method requires visitor_code and goal_id. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitor_code is usually identical to the one that was used when triggering the experiment.
El método track_conversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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])
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. | |
| goal_id (obligatorio) | Integer | ID del objetivo. | |
| revenue (opcional) | Float | Ingreso de la conversión. | 0 |
| negative (opcional) | Bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | Array<CustomData> | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | nil |
| isUniqueIdentifier (deprecated) | Bool | An optional parameter for specifying if the visitor_code is a unique identifier. | false |
metadata values are accessible through raw data exports and the results page.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() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the track_conversion() method.En el siguiente ejemplo, 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’).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")])
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. 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.
Consulte experimentación híbrida para más información sobre cómo implementar este método.
engine_tracking_code = kameleoon_client.get_engine_tracking_code(visitor_code)
- To use this feature, implement both the Ruby SDK and Kameleoon Engine.js. 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. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
getVisitorCode, as long as you add the corresponding experiment assignments to window.kameleoonQueue..
- You can insert the returned tracking code directly into an HTML
<script> tag.
<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>
En este ejemplo, 123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code (obligatorio) | String | Identificador único del visitante. |
Valor de retorno
| Tipo | Descripción |
|---|
String | Código JavaScript para insertar en la página. |
Events
on_update_configuration()
El método on_update_configuration() le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
kameleoon_client.on_update_configuration(
# configuration was updated
)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| handler | Callable | The handler that will be called when the configuration is updated using a real-time configuration event. |
Tipos de datos
Browser
El conjunto de datos Browser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
| Nombre | Tipo | Descripción |
|---|
| browser_type (obligatorio) | BrowserType | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. |
| version (opcional) | Float | Version of the browser, floating point number represents major and minor version of the browser |
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
| Nombre | Tipo | Descripción |
|---|
| url | String | URL of the page viewed. Este campo es obligatorio. |
| title | String | Title of the page viewed. Este campo es obligatorio. |
| referrers | Array | Referrers de las páginas vistas. Este campo es opcional. |
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 you create for a site would have the ID 0, not 1.
kameleoon_client.add_data(visitor_code, Kameleoon::PageView.new("https://url.com", "title", [3]))
Conversion
El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Each visitor can have multiple
Conversion objects.
- You can find the
goal_id in the Kameleoon app.
| Nombre | Tipo | Descripción | Default |
|---|
| goal_id (obligatorio) | Integer | ID del objetivo. | |
| revenue (opcional) | Float | Revenue of the conversion | 0 |
| negative (opcional) | Bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | Array<CustomData> | Metadatos de la conversión. | nil |
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 or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | Default |
|---|
| index/name (obligatorio) | Integer/String | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| values (obligatorio) | Array | Values of the custom data to be stored. | |
| overwrite (opcional) | Boolean | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | true |
- Each visitor can only have one
CustomData for each unique index. Adding another CustomData with the same index will replace the existing CustomData.
- The custom data
index can be found in the Custom Data dashboard under the “INDEX” column.
- To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option Use this data only locally for targeting purposes when creating custom data.
- Adding a
CustomData instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
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
| Nombre | Tipo | Descripción |
|---|
| device | DeviceType | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |
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. Para más detalles, consulte the help article on bot filtering.
Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
| Nombre | Tipo | Descripción |
|---|
| value | String | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |
kameleoon_client.add_data(visitor_code, Kameleoon::UserAgent.new("Your User Agent"))
UniqueIdentifier
Si no añade UniqueIdentifier para un visitante, se utiliza visitor_code como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
UniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
| Nombre | Tipo | Descripción |
|---|
| value | Boolean | Parameter for specifying if the visitor_code is a unique identifier. Este campo es obligatorio. |
kameleoon_client.add_data(visitorCode, Kameleoon::UniqueIdentifier.new(true))
OperatingSystem
OperatingSystem contains information about the visitor’s operating system.
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first.
| Nombre | Tipo | Descripción |
|---|
| type | OperatingSystemType | List of types: WINDOWS, MAC, IOS, LINUX, ANDROID, WINDOWS_PHONE. Este campo es obligatorio. |
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.
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first.
| Nombre | Tipo | Descripción |
|---|
| cookies | Hash | Hash object ({:cookie_name => cookie_value}) consisting of cookie keys and values. Este campo es obligatorio. |
cookie = Kameleoon::Cookie.new({ "k1" => "v1", "k2" => "v2" })
kameleoon_client.add_data(visitor_code, cookie)
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | String | The country of the visitor. |
| region (opcional) | String | The region of the visitor. |
| city (opcional) | String | The city of the visitor. |
| postal_code (opcional) | String | The postal code of the visitor. |
| latitude (opcional) | Float | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | Float | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
- Each visitor can have only one
Geolocation. Adding a second Geolocation overwrites the first one.
kameleoon_client.add_data(visitor_code, Kameleoon::Geolocation.new("France", "Île-de-France", "Paris"))
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
| Nombre | Tipo | Descripción |
|---|
| version (opcional) | String | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
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
El DataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| feature_flags | Hash<String, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| date_modified | Integer | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
# 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
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| environment_enabled | Bool | Indica si el feature flag está habilitado en el entorno actual. |
| 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 |
# 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
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| variations | Hash<String, Variation> | A map of Variation objects, keyed by variation keys. |
# 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).
| Nombre | Tipo | Descripción |
|---|
| 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. |
- The
Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
- Ensure that your code handles the case where
id or experiment_id may be nil, indicating a default variation.
- The
variables hash might be empty if no variables are associated with the variation.
# 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.
| Nombre | Tipo | Descripción |
|---|
| 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. |
# 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
These methods are deprecated and will be removed in SDK version 4.0.0.
get_feature_variation_key()
- 📨 Envía datos de seguimiento a Kameleoon
To get a feature variation key, call the get_feature_variation_key method.
Este método toma un 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.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
If you specify a visitor_code, the get_feature_variation_key method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | string | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Boolean | When true, the SDK links the flushed data to the visitor associated with the specified identifier. |
Valor de retorno
| Tipo | Descripción |
|---|
| string | Variation key of the feature flag that is registered for a given visitor_code. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| 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 | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o 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()
Este método solo acepta visitorCode como parámetro de entrada. El resultado solo contiene los feature flags activos para un visitante determinado.
active_feature_flag_list = kameleoon_client.get_active_feature_list_for_visitor(visitor_code)
Argumentos
| Name | Type | Description |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
Valor de retorno
| Type | Description |
|---|
| Array | List of feature flag keys which are active for a given visitor_code |
Excepciones lanzadas
| 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.
This method is deprecated and will be removed in SDK version 4.0.0. Use get_variations() instead.
active_features = kameleoon_client.get_active_features(visitor_code)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
Hash<String, Variation> | A hash that contains the assigned variations of the active features using the active feature IDs as keys. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| Kameleoon::Exception::VisitorCodeInvalid | Exception indicating that the provided visitor code is invalid (empty, or longer than 255 characters). |
get_feature_variable()
- 📨 Envía datos de seguimiento a Kameleoon
Previously called obtain_feature_variable - deprecated since SDK version 2.1.0 and will be removed in a future releases.
To get a variable of the variation key associated with a user, call the get_feature_variable method.
Este método toma un 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.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
If you specify a visitor_code, the get_feature_variable method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | string | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| variable_name | string | Name of the variable for which you want to get the value. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Boolean | When true, the SDK links the flushed data with to visitor associated with the specified identifier. |
Valor de retorno
| Tipo | Descripción |
|---|
| 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 |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| 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()
To retrieve the all feature variables, call the get_feature_variation_variables method. A feature variable can be changed using our web application.
Este método toma 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.
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
Argumentos
| Nombre | Tipo | Descripción |
|---|
| feature_key | string | Key of the feature flag you want to obtain. Este campo es obligatorio. |
| variation_key | string | Clave de la variación que desea obtener. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| 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). |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| 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 | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o 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()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
feature_list = kameleoon_client.get_feature_list
Valor de retorno
| Tipo | Descripción |
|---|
Array | List of feature flag keys |