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.



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

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::UrlProvider.new(site_code, Network::UrlProvider::DEFAULT_DATA_API_URL),
    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.



34
35
36
# File 'lib/kameleoon/kameleoon_client.rb', line 34

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:



114
115
116
117
118
# File 'lib/kameleoon/kameleoon_client.rb', line 114

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:



178
179
180
181
182
183
# File 'lib/kameleoon/kameleoon_client.rb', line 178

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:



152
153
154
155
156
157
158
159
# File 'lib/kameleoon/kameleoon_client.rb', line 152

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:



310
311
312
313
314
315
316
317
318
319
# File 'lib/kameleoon/kameleoon_client.rb', line 310

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



340
341
342
343
# File 'lib/kameleoon/kameleoon_client.rb', line 340

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



300
301
302
# File 'lib/kameleoon/kameleoon_client.rb', line 300

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:



222
223
224
225
226
227
228
229
230
231
# File 'lib/kameleoon/kameleoon_client.rb', line 222

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:



202
203
204
205
# File 'lib/kameleoon/kameleoon_client.rb', line 202

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:



247
248
249
250
251
252
253
254
255
256
257
# File 'lib/kameleoon/kameleoon_client.rb', line 247

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 (Int) (defaults to: @default_timeout)

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

Returns:

  • (Hash)

    Hash object of the json object.



271
272
273
274
# File 'lib/kameleoon/kameleoon_client.rb', line 271

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 (Int) (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.



289
290
291
292
293
294
# File 'lib/kameleoon/kameleoon_client.rb', line 289

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



90
91
92
# File 'lib/kameleoon/kameleoon_client.rb', line 90

def get_visitor_code(cookies, default_visitor_code = nil)
  @cookie_manager.get_or_add(cookies, default_visitor_code)
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



328
329
330
# File 'lib/kameleoon/kameleoon_client.rb', line 328

def on_update_configuration(handler)
  @update_configuration_handler = handler
end


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

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:



135
136
137
138
139
# File 'lib/kameleoon/kameleoon_client.rb', line 135

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



60
61
62
# File 'lib/kameleoon/kameleoon_client.rb', line 60

def wait_init
  @readiness.wait
end