Class: Optimizely::Project

Inherits:
Object
  • Object
show all
Defined in:
lib/optimizely.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(datafile = nil, event_dispatcher = nil, logger = nil, error_handler = nil, skip_json_validation = false, user_profile_service = nil, sdk_key = nil, config_manager = nil, notification_center = nil, event_processor = nil) ⇒ Project

Constructor for Projects.

Parameters:

  • datafile (defaults to: nil)
    • JSON string representing the project.

  • event_dispatcher (defaults to: nil)
    • Provides a dispatch_event method which if given a URL and params sends a request to it.

  • logger (defaults to: nil)
    • Optional component which provides a log method to log messages. By default nothing would be logged.

  • error_handler (defaults to: nil)
    • Optional component which provides a handle_error method to handle exceptions.

    By default all exceptions will be suppressed.

  • user_profile_service (defaults to: nil)
    • Optional component which provides methods to store and retreive user profiles.

  • skip_json_validation (defaults to: false)
    • Optional boolean param to skip JSON schema validation of the provided datafile.

  • config_manager (defaults to: nil)
    • Optional Responds to ‘config’ method.

  • notification_center (defaults to: nil)
    • Optional Instance of NotificationCenter.

  • event_processor (defaults to: nil)
    • Optional Responds to process.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/optimizely.rb', line 60

def initialize(
  datafile = nil,
  event_dispatcher = nil,
  logger = nil,
  error_handler = nil,
  skip_json_validation = false,
   = nil,
  sdk_key = nil,
  config_manager = nil,
  notification_center = nil,
  event_processor = nil
)
  @logger = logger || NoOpLogger.new
  @error_handler = error_handler || NoOpErrorHandler.new
  @event_dispatcher = event_dispatcher || EventDispatcher.new(logger: @logger, error_handler: @error_handler)
  @user_profile_service = 

  begin
    validate_instantiation_options
  rescue InvalidInputError => e
    @logger = SimpleLogger.new
    @logger.log(Logger::ERROR, e.message)
  end

  @notification_center = notification_center.is_a?(Optimizely::NotificationCenter) ? notification_center : NotificationCenter.new(@logger, @error_handler)

  @config_manager = if config_manager.respond_to?(:config)
                      config_manager
                    elsif sdk_key
                      HTTPProjectConfigManager.new(
                        sdk_key: sdk_key,
                        datafile: datafile,
                        logger: @logger,
                        error_handler: @error_handler,
                        skip_json_validation: skip_json_validation,
                        notification_center: @notification_center
                      )
                    else
                      StaticProjectConfigManager.new(datafile, @logger, @error_handler, skip_json_validation)
                    end

  @decision_service = DecisionService.new(@logger, @user_profile_service)

  @event_processor = if event_processor.respond_to?(:process)
                       event_processor
                     else
                       ForwardingEventProcessor.new(@event_dispatcher, @logger, @notification_center)
                     end
end

Instance Attribute Details

#config_managerObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def config_manager
  @config_manager
end

#decision_serviceObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def decision_service
  @decision_service
end

#error_handlerObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def error_handler
  @error_handler
end

#event_dispatcherObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def event_dispatcher
  @event_dispatcher
end

#event_processorObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def event_processor
  @event_processor
end

#loggerObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def logger
  @logger
end

#notification_centerObject (readonly)

Returns the value of attribute notification_center.



40
41
42
# File 'lib/optimizely.rb', line 40

def notification_center
  @notification_center
end

#stoppedObject (readonly)



42
43
44
# File 'lib/optimizely.rb', line 42

def stopped
  @stopped
end

Instance Method Details

#activate(experiment_key, user_id, attributes = nil) ⇒ Variation Key?

Buckets visitor and sends impression event to Optimizely.

Parameters:

  • experiment_key
    • Experiment which needs to be activated.

  • user_id
    • String ID for user.

  • attributes (defaults to: nil)
    • Hash representing user attributes and values to be recorded.

Returns:

  • (Variation Key)

    representing the variation the user will be bucketed in.

  • (nil)

    if experiment is not Running, if user is not in experiment, or if datafile is invalid.



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/optimizely.rb', line 119

def activate(experiment_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('activate').message)
    return nil
  end

  return nil unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      experiment_key: experiment_key,
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  config = project_config

  variation_key = get_variation_with_config(experiment_key, user_id, attributes, config)

  if variation_key.nil?
    @logger.log(Logger::INFO, "Not activating user '#{user_id}'.")
    return nil
  end

  # Create and dispatch impression event
  experiment = config.get_experiment_from_key(experiment_key)
  send_impression(config, experiment, variation_key, user_id, attributes)

  variation_key
end

#closeObject



519
520
521
522
523
524
525
# File 'lib/optimizely.rb', line 519

def close
  return if @stopped

  @stopped = true
  @config_manager.stop! if @config_manager.respond_to?(:stop!)
  @event_processor.stop! if @event_processor.respond_to?(:stop!)
end

#get_enabled_features(user_id, attributes = nil) ⇒ feature flag keys

Gets keys of all feature flags which are enabled for the user.

Parameters:

  • user_id
    • ID for user.

  • attributes (defaults to: nil)
    • Dict representing user attributes.

Returns:

  • (feature flag keys)

    A List of feature flag keys that are enabled for the user.



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/optimizely.rb', line 354

def get_enabled_features(user_id, attributes = nil)
  enabled_features = []
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_enabled_features').message)
    return enabled_features
  end

  return enabled_features unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  return enabled_features unless user_inputs_valid?(attributes)

  config = project_config

  config.feature_flags.each do |feature|
    enabled_features.push(feature['key']) if is_feature_enabled(
      feature['key'],
      user_id,
      attributes
    ) == true
  end
  enabled_features
end

#get_feature_variable(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ *?

Get the value of the specified variable in the feature flag.

Parameters:

  • feature_flag_key
    • String key of feature flag the variable belongs to

  • variable_key
    • String key of variable for which we are getting the value

  • user_id
    • String user ID

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (*)

    the type-casted variable value.

  • (nil)

    if the feature flag or variable are not found.



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/optimizely.rb', line 391

def get_feature_variable(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable').message)
    return nil
  end
  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    nil,
    user_id,
    attributes
  )

  variable_value
end

#get_feature_variable_boolean(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ Boolean?

Get the Boolean value of the specified variable in the feature flag.

Parameters:

  • feature_flag_key
    • String key of feature flag the variable belongs to

  • variable_key
    • String key of variable for which we are getting the string value

  • user_id
    • String user ID

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (Boolean)

    the boolean variable value.

  • (nil)

    if the feature flag or variable are not found.



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/optimizely.rb', line 443

def get_feature_variable_boolean(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_boolean').message)
    return nil
  end

  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    Optimizely::Helpers::Constants::VARIABLE_TYPES['BOOLEAN'],
    user_id,
    attributes
  )

  variable_value
end

#get_feature_variable_double(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ Boolean?

Get the Double value of the specified variable in the feature flag.

Parameters:

  • feature_flag_key
    • String key of feature flag the variable belongs to

  • variable_key
    • String key of variable for which we are getting the string value

  • user_id
    • String user ID

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (Boolean)

    the double variable value.

  • (nil)

    if the feature flag or variable are not found.



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/optimizely.rb', line 470

def get_feature_variable_double(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_double').message)
    return nil
  end

  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    Optimizely::Helpers::Constants::VARIABLE_TYPES['DOUBLE'],
    user_id,
    attributes
  )

  variable_value
end

#get_feature_variable_integer(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ Integer?

Get the Integer value of the specified variable in the feature flag.

Parameters:

  • feature_flag_key
    • String key of feature flag the variable belongs to

  • variable_key
    • String key of variable for which we are getting the string value

  • user_id
    • String user ID

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (Integer)

    variable value.

  • (nil)

    if the feature flag or variable are not found.



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/optimizely.rb', line 497

def get_feature_variable_integer(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_integer').message)
    return nil
  end

  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    Optimizely::Helpers::Constants::VARIABLE_TYPES['INTEGER'],
    user_id,
    attributes
  )

  variable_value
end

#get_feature_variable_string(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ String?

Get the String value of the specified variable in the feature flag.

Parameters:

  • feature_flag_key
    • String key of feature flag the variable belongs to

  • variable_key
    • String key of variable for which we are getting the string value

  • user_id
    • String user ID

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (String)

    the string variable value.

  • (nil)

    if the feature flag or variable are not found.



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/optimizely.rb', line 417

def get_feature_variable_string(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_string').message)
    return nil
  end
  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    Optimizely::Helpers::Constants::VARIABLE_TYPES['STRING'],
    user_id,
    attributes
  )

  variable_value
end

#get_forced_variation(experiment_key, user_id) ⇒ String

Gets the forced variation for a given user and experiment.

Parameters:

  • experiment_key
    • String - Key identifying the experiment.

  • user_id
    • String - The user ID to be used for bucketing.

Returns:

  • (String)

    The forced variation key.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/optimizely.rb', line 206

def get_forced_variation(experiment_key, user_id)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_forced_variation').message)
    return nil
  end

  return nil unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      experiment_key: experiment_key,
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  config = project_config

  forced_variation_key = nil
  forced_variation = @decision_service.get_forced_variation(config, experiment_key, user_id)
  forced_variation_key = forced_variation['key'] if forced_variation

  forced_variation_key
end

#get_optimizely_configObject



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/optimizely.rb', line 527

def get_optimizely_config
  # Get OptimizelyConfig object containing experiments and features data
  # Returns Object
  #
  # OptimizelyConfig Object Schema
  # {
  #   'experimentsMap' => {
  #     'my-fist-experiment' => {
  #       'id' => '111111',
  #       'key' => 'my-fist-experiment'
  #       'variationsMap' => {
  #         'variation_1' => {
  #           'id' => '121212',
  #           'key' => 'variation_1',
  #           'variablesMap' => {
  #             'age' => {
  #               'id' => '222222',
  #               'key' => 'age',
  #               'type' => 'integer',
  #               'value' => '0',
  #             }
  #           }
  #         }
  #       }
  #     }
  #   },
  #   'featuresMap' => {
  #     'awesome-feature' => {
  #       'id' => '333333',
  #       'key' => 'awesome-feature',
  #       'experimentsMap' => Object,
  #       'variablesMap' => Object,
  #     }
  #   },
  #   'revision' => '13',
  # }
  #
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_optimizely_config').message)
    return nil
  end

  # config_manager might not contain optimizely_config if its supplied by the consumer
  # Generating a new OptimizelyConfig object in this case as a fallback
  if @config_manager.respond_to?(:optimizely_config)
    @config_manager.optimizely_config
  else
    OptimizelyConfig.new(project_config).config
  end
end

#get_variation(experiment_key, user_id, attributes = nil) ⇒ variation key?

Gets variation where visitor will be bucketed.

Parameters:

  • experiment_key
    • Experiment for which visitor variation needs to be determined.

  • user_id
    • String ID for user.

  • attributes (defaults to: nil)
    • Hash representing user attributes.

Returns:

  • (variation key)

    where visitor will be bucketed.

  • (nil)

    if experiment is not Running, if user is not in experiment, or if datafile is invalid.



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/optimizely.rb', line 157

def get_variation(experiment_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_variation').message)
    return nil
  end

  return nil unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      experiment_key: experiment_key,
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  config = project_config

  get_variation_with_config(experiment_key, user_id, attributes, config)
end

#is_feature_enabled(feature_flag_key, user_id, attributes = nil) ⇒ True, False

Determine whether a feature is enabled. Sends an impression event if the user is bucketed into an experiment using the feature.

Parameters:

  • feature_flag_key
    • String unique key of the feature.

  • user_id
    • String ID of the user.

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

Returns:

  • (True)

    if the feature is enabled.

  • (False)

    if the feature is disabled.

  • (False)

    if the feature is not found.



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/optimizely.rb', line 283

def is_feature_enabled(feature_flag_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('is_feature_enabled').message)
    return false
  end

  return false unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      feature_flag_key: feature_flag_key,
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  return false unless user_inputs_valid?(attributes)

  config = project_config

  feature_flag = config.get_feature_flag_from_key(feature_flag_key)
  unless feature_flag
    @logger.log(Logger::ERROR, "No feature flag was found for key '#{feature_flag_key}'.")
    return false
  end

  decision = @decision_service.get_variation_for_feature(config, feature_flag, user_id, attributes)

  feature_enabled = false
  source_string = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']
  if decision.is_a?(Optimizely::DecisionService::Decision)
    variation = decision['variation']
    feature_enabled = variation['featureEnabled']
    if decision.source == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
      source_string = Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
      source_info = {
        experiment_key: decision.experiment['key'],
        variation_key: variation['key']
      }
      # Send event if Decision came from an experiment.
      send_impression(config, decision.experiment, variation['key'], user_id, attributes)
    else
      @logger.log(Logger::DEBUG,
                  "The user '#{user_id}' is not being experimented on in feature '#{feature_flag_key}'.")
    end
  end

  @notification_center.send_notifications(
    NotificationCenter::NOTIFICATION_TYPES[:DECISION],
    Helpers::Constants::DECISION_NOTIFICATION_TYPES['FEATURE'],
    user_id, (attributes || {}),
    feature_key: feature_flag_key,
    feature_enabled: feature_enabled,
    source: source_string,
    source_info: source_info || {}
  )

  if feature_enabled == true
    @logger.log(Logger::INFO,
                "Feature '#{feature_flag_key}' is enabled for user '#{user_id}'.")
    return true
  end

  @logger.log(Logger::INFO,
              "Feature '#{feature_flag_key}' is not enabled for user '#{user_id}'.")
  false
end

#is_validObject



514
515
516
517
# File 'lib/optimizely.rb', line 514

def is_valid
  config = project_config
  config.is_a?(Optimizely::ProjectConfig)
end

#set_forced_variation(experiment_key, user_id, variation_key) ⇒ Boolean

Force a user into a variation for a given experiment.

Parameters:

  • experiment_key
    • String - key identifying the experiment.

  • user_id
    • String - The user ID to be used for bucketing.

  • variation_key
    • The variation key specifies the variation which the user will

    be forced into. If nil, then clear the existing experiment-to-variation mapping.

Returns:

  • (Boolean)

    indicates if the set completed successfully.



184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/optimizely.rb', line 184

def set_forced_variation(experiment_key, user_id, variation_key)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('set_forced_variation').message)
    return nil
  end

  input_values = {experiment_key: experiment_key, user_id: user_id}
  input_values[:variation_key] = variation_key unless variation_key.nil?
  return false unless Optimizely::Helpers::Validator.inputs_valid?(input_values, @logger, Logger::ERROR)

  config = project_config

  @decision_service.set_forced_variation(config, experiment_key, user_id, variation_key)
end

#track(event_key, user_id, attributes = nil, event_tags = nil) ⇒ Object

Send conversion event to Optimizely.

Parameters:

  • event_key
    • Event key representing the event which needs to be recorded.

  • user_id
    • String ID for user.

  • attributes (defaults to: nil)
    • Hash representing visitor attributes and values which need to be recorded.

  • event_tags (defaults to: nil)
    • Hash representing metadata associated with the event.



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/optimizely.rb', line 235

def track(event_key, user_id, attributes = nil, event_tags = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('track').message)
    return nil
  end

  return nil unless Optimizely::Helpers::Validator.inputs_valid?(
    {
      event_key: event_key,
      user_id: user_id
    }, @logger, Logger::ERROR
  )

  return nil unless user_inputs_valid?(attributes, event_tags)

  config = project_config

  event = config.get_event_from_key(event_key)
  unless event
    @logger.log(Logger::INFO, "Not tracking user '#{user_id}' for event '#{event_key}'.")
    return nil
  end

  user_event = UserEventFactory.create_conversion_event(config, event, user_id, attributes, event_tags)
  @event_processor.process(user_event)
  @logger.log(Logger::INFO, "Tracking event '#{event_key}' for user '#{user_id}'.")

  if @notification_center.notification_count(NotificationCenter::NOTIFICATION_TYPES[:TRACK]).positive?
    log_event = EventFactory.create_log_event(user_event, @logger)
    @notification_center.send_notifications(
      NotificationCenter::NOTIFICATION_TYPES[:TRACK],
      event_key, user_id, attributes, event_tags, log_event
    )
  end
  nil
end