Class: Kameleoon::KameleoonClient

Inherits:
Object
  • Object
show all
Includes:
Exception
Defined in:
lib/kameleoon/kameleoon_client.rb

Overview

Client for Kameleoon

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(site_code, config) ⇒ KameleoonClient

You should create KameleoonClient with the Client Factory only.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/kameleoon/kameleoon_client.rb', line 41

def initialize(site_code, config)
  raise Exception::SiteCodeIsEmpty, 'Provided site_sode is empty' if site_code&.empty? != false

  @site_code = site_code
  @config = config
  @real_time_configuration_service = nil
  @update_configuration_handler = nil
  @fetch_configuration_update_job = nil
  @data_file = Configuration::DataFile.new(config.environment)
  @visitor_manager = Kameleoon::DataManager::VisitorManager.new(config.session_duration_second)
  @hybrid_manager = Kameleoon::Hybrid::ManagerImpl.new(HYBRID_EXPIRATION_TIME, method(:log))
  @network_manager = Network::NetworkManager.new(
    config.environment,
    config.default_timeout_millisecond,
    Network::AccessTokenSourceFactory.new(config.client_id, config.client_secret, method(:log)),
    Network::UrlProvider.new(site_code),
    method(:log)
  )
  @warehouse_manager = Managers::Warehouse::WarehouseManager.new(@network_manager, @visitor_manager, method(:log))
  @cookie_manager = Network::Cookie::CookieManager.new(config.top_level_domain)
  @readiness = ClientReadiness.new
end

Instance Attribute Details

#site_codeObject (readonly)

Returns the value of attribute site_code.



36
37
38
# File 'lib/kameleoon/kameleoon_client.rb', line 36

def site_code
  @site_code
end

Instance Method Details

#add_data(visitor_code, *args) ⇒ Object

Associate various data to a visitor.

Note that this method doesn’t return any value and doesn’t interact with the Kameleoon back-end servers by itself. Instead, the declared data is saved for future sending via the flush method. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of the flush method.

Parameters:

  • visitor_code (String)

    Visitor code

  • data (...Data)

    Data to associate with the visitor code

Raises:



118
119
120
121
122
# File 'lib/kameleoon/kameleoon_client.rb', line 118

def add_data(visitor_code, *args)
  Utils::VisitorCode.validate(visitor_code)
  visitor = @visitor_manager.get_or_create_visitor(visitor_code)
  visitor.add_data(method(:log), *args)
end

#feature_active?(visitor_code, feature_key) ⇒ Boolean

Check if feature is active for a given visitor code

This method takes a visitor_code and feature_key as mandatory arguments to check if the specified feature will be active for a given user. If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous feature flag value. You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Parameters:

  • visitor_code (String)

    Unique identifier of the user. This field is mandatory.

  • feature_key (String)

    Key of the feature flag you want to expose to a user. This field is mandatory.

Returns:

  • (Boolean)

Raises:



182
183
184
185
186
187
# File 'lib/kameleoon/kameleoon_client.rb', line 182

def feature_active?(visitor_code, feature_key)
  _, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation_key != Kameleoon::Configuration::VariationType::VARIATION_OFF
rescue Exception::FeatureEnvironmentDisabled
  false
end

#flush(visitor_code = nil) ⇒ Object

Flush the associated data.

The data added with the method add_data, is not directly sent to the kameleoon servers. It’s stored and accumulated until it is sent automatically by the trigger_experiment or track_conversion methods. With this method you can manually send it.

Parameters:

  • visitor_code (String) (defaults to: nil)

    Optional field - Visitor code, without visitor code it flush all of the data

Raises:



156
157
158
159
160
161
162
163
# File 'lib/kameleoon/kameleoon_client.rb', line 156

def flush(visitor_code = nil)
  Utils::VisitorCode.validate(visitor_code) unless visitor_code.nil?
  if visitor_code.nil?
    @visitor_manager.enumerate { |visitor_code, visitor| _send_tracking_request(visitor_code, visitor, false) }
  else
    _send_tracking_request(visitor_code, nil, true)
  end
end

#get_active_feature_list_for_visitor(visitor_code) ⇒ Array

Returns a list of active feature flag keys for a visitor

Returns:

  • (Array)

    array of active feature flag keys for a visitor

Raises:



341
342
343
344
345
346
347
348
349
350
# File 'lib/kameleoon/kameleoon_client.rb', line 341

def get_active_feature_list_for_visitor(visitor_code)
  Utils::VisitorCode.validate(visitor_code)
  list_keys = []
  @data_file.feature_flags.each do |feature_key, feature_flag|
    variation, rule, = _calculate_variation_key_for_feature(visitor_code, feature_flag)
    variation_key = _get_variation_key(variation, rule, feature_flag)
    list_keys.push(feature_key) if variation_key != Kameleoon::Configuration::VariationType::VARIATION_OFF
  end
  list_keys
end

#get_engine_tracking_code(visitor_code) ⇒ String

The ‘get_engine_tracking_code` returns the JavasScript code to be inserted in your page to send automatically the exposure events to the analytics solution you are using.

the exposure events to the analytics solution you are using.

Parameters:

  • visitor_code (String)

    The user’s unique identifier. This field is mandatory.

Returns:

  • (String)

    JavasScript code to be inserted in your page to send automatically



371
372
373
374
# File 'lib/kameleoon/kameleoon_client.rb', line 371

def get_engine_tracking_code(visitor_code)
  visitor_variations = @visitor_manager.get_visitor(visitor_code)&.variations
  @hybrid_manager.get_engine_tracking_code(visitor_variations)
end

#get_feature_listArray

Returns a list of all feature flag keys

Returns:

  • (Array)

    array of all feature flag keys



331
332
333
# File 'lib/kameleoon/kameleoon_client.rb', line 331

def get_feature_list # rubocop:disable Naming/AccessorMethodName
  @data_file.feature_flags.keys
end

#get_feature_variable(visitor_code, feature_key, variable_name) ⇒ Object

Retrieves a feature variable value from assigned for visitor variation

A feature variable can be changed easily via our web application.

the current environment

Parameters:

  • visitor_code (String)
  • feature_key (String)
  • variable_name (String)

Raises:



226
227
228
229
230
231
232
233
234
235
# File 'lib/kameleoon/kameleoon_client.rb', line 226

def get_feature_variable(visitor_code, feature_key, variable_name)
  feature_flag, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation = feature_flag.get_variation_key(variation_key)
  variable = variation&.get_variable_by_key(variable_name)
  if variable.nil?
    raise Exception::FeatureVariableNotFound.new(variable_name),
          "Feature variable #{variable_name} not found"
  end
  _parse_feature_variable(variable)
end

#get_feature_variation_key(visitor_code, feature_key) ⇒ Object

get_feature_variation_key returns a variation key for visitor code

This method takes a visitorCode and featureKey as mandatory arguments and returns a variation assigned for a given visitor If such a user has never been associated with any feature flag rules, the SDK returns a default variation key You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

the current environment

Parameters:

  • visitor_code (String)
  • feature_key (String)

Raises:



206
207
208
209
# File 'lib/kameleoon/kameleoon_client.rb', line 206

def get_feature_variation_key(visitor_code, feature_key)
  _, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation_key
end

#get_feature_variation_variables(feature_key, variation_key) ⇒ Object

Retrieves all feature variable values for a given variation

This method takes a feature_key and variation_key as mandatory arguments and returns a list of variables for a given variation key A feature variable can be changed easily via our web application.

Parameters:

  • feature_key (String)
  • variation_key (String)

Raises:



251
252
253
254
255
256
257
258
259
260
261
# File 'lib/kameleoon/kameleoon_client.rb', line 251

def get_feature_variation_variables(feature_key, variation_key)
  feature_flag = @data_file.get_feature_flag(feature_key)
  variation = feature_flag.get_variation_key(variation_key)
  if variation.nil?
    raise Exception::FeatureVariationNotFound.new(variation_key),
          "Variation key #{variation_key} not found"
  end
  variables = {}
  variation.variables.each { |var| variables[var.key] = _parse_feature_variable(var) }
  variables
end

#get_remote_data(key, timeout = @default_timeout) ⇒ Hash

The get_remote_data method allows you to retrieve data (according to a key passed as argument) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

This field is optional.

Parameters:

  • key (String)

    Key you want to retrieve data. This field is mandatory.

  • timeout (Integer) (defaults to: @default_timeout)

    Timeout for request (in milliseconds). Equals default_timeout in a config file.

Returns:

  • (Hash)

    Hash object of the json object.



275
276
277
278
# File 'lib/kameleoon/kameleoon_client.rb', line 275

def get_remote_data(key, timeout = @default_timeout)
  response = @network_manager.get_remote_data(key, timeout)
  JSON.parse(response) if response
end

#get_remote_visitor_data(visitor_code, timeout = nil, add_data: true) ⇒ Array

The get_remote_visitor_data is a method for retrieving custom data for the latest visit of ‘visitor_code` from Kameleoon Data API and optionally adding it to the storage so that other methods could decide whether the current visitor is targeted or not.

This field is mandatory. for a visitor. If not specified, the default value is ‘True`. This field is optional. This field is optional.

Parameters:

  • visitor_code (String)

    The visitor code for which you want to retrieve the assigned data.

  • add_data (Bool) (defaults to: true)

    A boolean indicating whether the method should automatically add retrieved data

  • timeout (Integer) (defaults to: nil)

    Timeout for request (in milliseconds). Equals default_timeout in a config file.

Returns:

  • (Array)

    An array of data assigned to the given visitor.



293
294
295
296
297
298
# File 'lib/kameleoon/kameleoon_client.rb', line 293

def get_remote_visitor_data(visitor_code, timeout = nil, add_data: true)
  response = @network_manager.get_remote_visitor_data(visitor_code, timeout)
  data_array = parse_custom_data_array(visitor_code, response)
  add_data(visitor_code, *data_array) if add_data && !data_array.empty?
  data_array
end

#get_visitor_code(cookies, default_visitor_code = nil) ⇒ String

Note:

The implementation logic is described here:

Obtain a visitor code.

This method should be called to obtain the Kameleoon visitor_code for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier. If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the default_visitor_code argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table. In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.

cookies = => ‘1234asdf4321fdsa’ visitor_code = get_visitor_code(cookies, ‘my-domaine.com’)

Parameters:

  • cookies (Hash)

    Cookies of the request.

  • top_level_domain (String)

    Top level domain of your website, settled while writing cookie.

  • default_visitor_code (String) (defaults to: nil)
    • Optional - Define your default visitor_code (maximum length 100 chars).

Returns:

  • (String)

    visitor code



94
95
96
# File 'lib/kameleoon/kameleoon_client.rb', line 94

def get_visitor_code(cookies, default_visitor_code = nil)
  @cookie_manager.get_or_add(cookies, default_visitor_code)
end

#get_visitor_warehouse_audience(visitor_code, custom_data_index, timeout = nil, warehouse_key: nil) ⇒ Kameleoon::CustomData

Retrieves data associated with a visitor’s warehouse audiences and adds it to the visitor. 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 <a href=“help.kameleoon.com/warehouse-audience-targeting/”>warehouse targeting documentation</a> for additional details. The method returns a `CustomData` object, confirming that the data has been added to the visitor and is available for targeting purposes.

This field is mandatory. your BigQuery Audiences. This field is mandatory. This field is optional. This field is optional.

Parameters:

  • visitor_code (String)

    A unique visitor identification string, can’t exceed 255 characters length.

  • custom_data_index (Integer)

    An integer representing the index of the custom data you want to use to target

  • warehouse_key (String) (defaults to: nil)

    A key to identify the warehouse data, typically your internal user ID.

  • timeout (Integer) (defaults to: nil)

    Timeout for request (in milliseconds). Equals default_timeout in a config file.

Returns:

  • (Kameleoon::CustomData)

    A ‘CustomData` instance confirming that the data has been added to the visitor.

Raises:



323
324
325
# File 'lib/kameleoon/kameleoon_client.rb', line 323

def get_visitor_warehouse_audience(visitor_code, custom_data_index, timeout = nil, warehouse_key: nil)
  @warehouse_manager.get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key, timeout)
end

#on_update_configuration(handler) ⇒ Object

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

is updated using a real-time configuration event.

Parameters:

  • handler (Callable | NilClass)

    The handler that will be called when the configuration



359
360
361
# File 'lib/kameleoon/kameleoon_client.rb', line 359

def on_update_configuration(handler)
  @update_configuration_handler = handler
end


98
99
100
101
102
103
# File 'lib/kameleoon/kameleoon_client.rb', line 98

def set_legal_consent(visitor_code, consent, cookies = nil)
  Utils::VisitorCode.validate(visitor_code)
  visitor = @visitor_manager.get_or_create_visitor(visitor_code)
  visitor.legal_consent = consent
  @cookie_manager.update(visitor_code, consent, cookies)
end

#track_conversion(visitor_code, goal_id, revenue = 0.0) ⇒ Object

Track conversions on a particular goal

This method requires visitor_code and goal_id to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitor_code usually is identical to the one that was used when triggering the experiment. The track_conversion method doesn’t return any value. This method is non-blocking as the server call is made asynchronously.

Parameters:

  • visitor_code (String)

    Visitor code

  • goal_id (Integer)

    Id of the goal

  • revenue (Float) (defaults to: 0.0)

    Optional - Revenue of the conversion.

Raises:



139
140
141
142
143
# File 'lib/kameleoon/kameleoon_client.rb', line 139

def track_conversion(visitor_code, goal_id, revenue = 0.0)
  Utils::VisitorCode.validate(visitor_code)
  add_data(visitor_code, Conversion.new(goal_id, revenue))
  flush(visitor_code)
end

#wait_initObject



64
65
66
# File 'lib/kameleoon/kameleoon_client.rb', line 64

def wait_init
  @readiness.wait
end