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:Configure the client
You provide credentials for the Ruby SDK using a configuration file, which you can also use to customize the SDK’s behavior. You can start with our sample configuration file. 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.
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 theget_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 theget_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 theadd_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étodotrack_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 theget_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 theget_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.
Device A
Device B
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, utiliceCustomData 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 addedUniqueIdentifier(true)- to retrieve data for all linked visitors.track_conversion()orflush()with addedUniqueIdentifier(true)data - to track some data for specific visitor that is associated with another visitor.
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.
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:- 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 aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (for example, the newuserIdoraccountId).
- Bucketing logic: Once a custom bucketing key is provided through the
add_data()method, all hash calculations for assigning users to variations will use thisnewVisitorCode(your custom key) instead of the defaultvisitor_code. Using thenewVisitorCodemeans 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 originalvisitor_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.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.
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.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 espera la inicialización del cliente Kameleoon. Este método le permite comprobar si el cliente se ha inicializado correctamente antes de proceder con otras operaciones.
Una vez que el cliente se ha inicializado, wait_init devuelve el resultado inmediatamente. Si la obtención inicial de la configuración falla, el cliente sigue reintentándolo en segundo plano, por lo que wait_init devuelve el resultado en cuanto una obtención tiene éxito. La espera siempre está limitada por un tiempo de expiración, por lo que nunca se bloquea indefinidamente: si el tiempo de expiración transcurre antes de que se cargue la configuración, wait_init devuelve false.
Argumentos
| Nombre | Tipo | Descripción | Valor por defecto |
|---|---|---|---|
timeout_millisecond (opcional) | Integer | Tiempo máximo de espera, en milisegundos. | default_timeout_millisecond |
Valor de retorno
| Tipo | Descripción |
|---|---|
Boolean | true si la instancia del cliente Kameleoon se inicializó correctamente, de lo contrario false (por ejemplo, si el tiempo de expiración transcurrió antes de que se completara la inicialización). |
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.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.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)
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.
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)
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_activeis set totrue, the methodget_variations()will return feature flags variations provided the user is not bucketed with theoffvariation. - El parámetro
trackcontrola si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set totrue. Si se establece enfalse, el seguimiento estará deshabilitado.
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.
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 specificVariation 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.
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
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.
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 objetoDataFile.
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.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.
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
kameleoonSimulationFFDatamanualmente.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
kameleoonSimulationFFData siga este formato:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación convarIddel experimentoexpIdpara elfeatureKeyindicado.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para elfeatureKeyindicado.
encodeURIComponent.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étodoadd_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.
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.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.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.
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.
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.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étodoget_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 specifiedvisitor_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.
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 theconsent 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.
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 aset_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
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.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’).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 theget_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.
- 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 towindow.kameleoonQueue.. - You can insert the returned tracking code directly into an HTML
<script>tag.
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étodoon_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.
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 datosBrowser 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 |
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.
Conversion
El conjunto de datosConversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
| 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 |
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
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existingCustomData. - The custom data
indexcan 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
CustomDatainstance 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.
Device
| Nombre | Tipo | Descripción |
|---|---|---|
| device | DeviceType | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |
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 theUserAgent 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. |
UniqueIdentifier
Si no añadeUniqueIdentifier 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. |
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. |
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. |
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. |
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
| 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. |
Returned Types
DataFile
ElDataFile 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. |
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 |
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. |
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
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
idorexperiment_idmay benil, indicating a default variation. - The
variableshash might be empty if no variables are associated with the variation.
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. |
Deprecated methods
get_feature_variation_key()
- 📨 Envía datos de seguimiento a Kameleoon
Use
get_variation() instead.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.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()
Use
get_active_features() instead.visitorCode como parámetro de entrada. El resultado solo contiene los feature flags activos para un visitante determinado.
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.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
Use
get_variation() instead.Previously called
obtain_feature_variable - deprecated since SDK version 2.1.0 and will be removed in a future releases.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.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()
Use
get_variation() instead.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.
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.Valor de retorno
| Tipo | Descripción |
|---|---|
Array | List of feature flag keys |