Class: Optimizely::Project

Inherits:
Object
  • Object
show all
Includes:
Decide
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, default_decide_options = []) ⇒ 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.



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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/optimizely.rb', line 66

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,
  default_decide_options = []
)
  @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 = 
  @default_decide_options = []

  if default_decide_options.is_a? Array
    @default_decide_options = default_decide_options.clone
  else
    @logger.log(Logger::DEBUG, 'Provided default decide options is not an array.')
    @default_decide_options = []
  end

  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)



48
49
50
# File 'lib/optimizely.rb', line 48

def config_manager
  @config_manager
end

#decision_serviceObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

def decision_service
  @decision_service
end

#error_handlerObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

def error_handler
  @error_handler
end

#event_dispatcherObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

def event_dispatcher
  @event_dispatcher
end

#event_processorObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

def event_processor
  @event_processor
end

#loggerObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

def logger
  @logger
end

#notification_centerObject (readonly)

Returns the value of attribute notification_center.



46
47
48
# File 'lib/optimizely.rb', line 46

def notification_center
  @notification_center
end

#stoppedObject (readonly)



48
49
50
# File 'lib/optimizely.rb', line 48

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.



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
# File 'lib/optimizely.rb', line 303

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, '', experiment_key, true,
    Optimizely::DecisionService::DECISION_SOURCES['EXPERIMENT'], user_id, attributes
  )

  variation_key
end

#closeObject



806
807
808
809
810
811
812
# File 'lib/optimizely.rb', line 806

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

#create_user_context(user_id, attributes = nil) ⇒ OptimizelyUserContext?

Create a context of the user for which decision APIs will be called.

A user context will be created successfully even when the SDK is not fully configured yet.

Parameters:

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

  • attributes (defaults to: nil)
    • A Hash representing user attribute names and values.

Returns:

  • (OptimizelyUserContext)

    An OptimizelyUserContext associated with this OptimizelyClient.

  • (nil)

    If user attributes are not in valid format.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/optimizely.rb', line 135

def create_user_context(user_id, attributes = nil)
  # We do not check for is_valid here as a user context can be created successfully
  # even when the SDK is not fully configured.

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

  # validate attributes
  return nil unless user_inputs_valid?(attributes)

  user_context = OptimizelyUserContext.new(self, user_id, attributes)
  user_context
end

#decide(user_context, key, decide_options = []) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/optimizely.rb', line 153

def decide(user_context, key, decide_options = [])
  # raising on user context as it is internal and not provided directly by the user.
  raise if user_context.class != OptimizelyUserContext

  reasons = []

  # check if SDK is ready
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide').message)
    reasons.push(OptimizelyDecisionMessage::SDK_NOT_READY)
    return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
  end

  # validate that key is a string
  unless key.is_a?(String)
    @logger.log(Logger::ERROR, 'Provided key is invalid')
    reasons.push(format(OptimizelyDecisionMessage::FLAG_KEY_INVALID, key))
    return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
  end

  # validate that key maps to a feature flag
  config = project_config
  feature_flag = config.get_feature_flag_from_key(key)
  unless feature_flag
    @logger.log(Logger::ERROR, "No feature flag was found for key '#{key}'.")
    reasons.push(format(OptimizelyDecisionMessage::FLAG_KEY_INVALID, key))
    return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
  end

  # merge decide_options and default_decide_options
  if decide_options.is_a? Array
    decide_options += @default_decide_options
  else
    @logger.log(Logger::DEBUG, 'Provided decide options is not an array. Using default decide options.')
    decide_options = @default_decide_options
  end

  # Create Optimizely Decision Result.
  user_id = user_context.user_id
  attributes = user_context.user_attributes
  variation_key = nil
  feature_enabled = false
  rule_key = nil
  flag_key = key
  all_variables = {}
  decision_event_dispatched = false
  experiment = nil
  decision_source = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']

  decision, reasons_received = @decision_service.get_variation_for_feature(config, feature_flag, user_id, attributes, decide_options)
  reasons.push(*reasons_received)

  # Send impression event if Decision came from a feature test and decide options doesn't include disableDecisionEvent
  if decision.is_a?(Optimizely::DecisionService::Decision)
    experiment = decision.experiment
    rule_key = experiment['key']
    variation = decision['variation']
    variation_key = variation['key']
    feature_enabled = variation['featureEnabled']
    decision_source = decision.source
  end

  unless decide_options.include? OptimizelyDecideOption::DISABLE_DECISION_EVENT
    if decision_source == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST'] || config.send_flag_decisions
      send_impression(config, experiment, variation_key || '', flag_key, rule_key || '', feature_enabled, decision_source, user_id, attributes)
      decision_event_dispatched = true
    end
  end

  # Generate all variables map if decide options doesn't include excludeVariables
  unless decide_options.include? OptimizelyDecideOption::EXCLUDE_VARIABLES
    feature_flag['variables'].each do |variable|
      variable_value = get_feature_variable_for_variation(key, feature_enabled, variation, variable, user_id)
      all_variables[variable['key']] = Helpers::VariableType.cast_value_to_type(variable_value, variable['type'], @logger)
    end
  end

  should_include_reasons = decide_options.include? OptimizelyDecideOption::INCLUDE_REASONS

  # Send notification
  @notification_center.send_notifications(
    NotificationCenter::NOTIFICATION_TYPES[:DECISION],
    Helpers::Constants::DECISION_NOTIFICATION_TYPES['FLAG'],
    user_id, (attributes || {}),
    flag_key: flag_key,
    enabled: feature_enabled,
    variables: all_variables,
    variation_key: variation_key,
    rule_key: rule_key,
    reasons: should_include_reasons ? reasons : [],
    decision_event_dispatched: decision_event_dispatched
  )

  OptimizelyDecision.new(
    variation_key: variation_key,
    enabled: feature_enabled,
    variables: all_variables,
    rule_key: rule_key,
    flag_key: flag_key,
    user_context: user_context,
    reasons: should_include_reasons ? reasons : []
  )
end

#decide_all(user_context, decide_options = []) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/optimizely.rb', line 257

def decide_all(user_context, decide_options = [])
  # raising on user context as it is internal and not provided directly by the user.
  raise if user_context.class != OptimizelyUserContext

  # check if SDK is ready
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide_all').message)
    return {}
  end

  keys = []
  project_config.feature_flags.each do |feature_flag|
    keys.push(feature_flag['key'])
  end
  decide_for_keys(user_context, keys, decide_options)
end

#decide_for_keys(user_context, keys, decide_options = []) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/optimizely.rb', line 274

def decide_for_keys(user_context, keys, decide_options = [])
  # raising on user context as it is internal and not provided directly by the user.
  raise if user_context.class != OptimizelyUserContext

  # check if SDK is ready
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide_for_keys').message)
    return {}
  end

  enabled_flags_only = (!decide_options.nil? && (decide_options.include? OptimizelyDecideOption::ENABLED_FLAGS_ONLY)) || (@default_decide_options.include? OptimizelyDecideOption::ENABLED_FLAGS_ONLY)

  decisions = {}
  keys.each do |key|
    decision = decide(user_context, key, decide_options)
    decisions[key] = decision unless enabled_flags_only && !decision.enabled
  end
  decisions
end

#get_all_feature_variables(feature_flag_key, user_id, attributes = nil) ⇒ Dict?

Get values of all the variables in the feature flag and returns them in a Dict

Parameters:

  • feature_flag_key
    • String key of feature flag

  • user_id
    • String user ID

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

Returns:

  • (Dict)

    the Dict containing all the varible values

  • (nil)

    if the feature flag is not found.



718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'lib/optimizely.rb', line 718

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

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

  return nil 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::INFO, "No feature flag was found for key '#{feature_flag_key}'.")
    return nil
  end

  decision, = @decision_service.get_variation_for_feature(config, feature_flag, user_id, attributes)
  variation = decision ? decision['variation'] : nil
  feature_enabled = variation ? variation['featureEnabled'] : false
  all_variables = {}

  feature_flag['variables'].each do |variable|
    variable_value = get_feature_variable_for_variation(feature_flag_key, feature_enabled, variation, variable, user_id)
    all_variables[variable['key']] = Helpers::VariableType.cast_value_to_type(variable_value, variable['type'], @logger)
  end

  source_string = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']
  if decision && decision['source'] == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
    source_info = {
      experiment_key: decision.experiment['key'],
      variation_key: variation['key']
    }
    source_string = Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
  end

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

  all_variables
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.



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
# File 'lib/optimizely.rb', line 550

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.



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/optimizely.rb', line 587

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.



665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/optimizely.rb', line 665

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.



692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/optimizely.rb', line 692

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.



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/optimizely.rb', line 784

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_json(feature_flag_key, variable_key, user_id, attributes = nil) ⇒ Dict?

Get the Json value of the specified variable in the feature flag in a Dict.

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:

  • (Dict)

    the Dict containing variable value.

  • (nil)

    if the feature flag or variable are not found.



639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/optimizely.rb', line 639

def get_feature_variable_json(feature_flag_key, variable_key, user_id, attributes = nil)
  unless is_valid
    @logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_json').message)
    return nil
  end
  variable_value = get_feature_variable_for_type(
    feature_flag_key,
    variable_key,
    Optimizely::Helpers::Constants::VARIABLE_TYPES['JSON'],
    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.



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'lib/optimizely.rb', line 613

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.



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/optimizely.rb', line 393

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



814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# File 'lib/optimizely.rb', line 814

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.



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/optimizely.rb', line 344

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.



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/optimizely.rb', line 470

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 a feature test.
      send_impression(
        config, decision.experiment, variation['key'], feature_flag_key, decision.experiment['key'], feature_enabled, source_string, user_id, attributes
      )
    elsif decision.source == Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT'] && config.send_flag_decisions
      send_impression(
        config, decision.experiment, variation['key'], feature_flag_key, decision.experiment['key'], feature_enabled, source_string, user_id, attributes
      )
    end
  end

  if decision.nil? && config.send_flag_decisions
    send_impression(
      config, nil, '', feature_flag_key, '', feature_enabled, source_string, user_id, attributes
    )
  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



801
802
803
804
# File 'lib/optimizely.rb', line 801

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.



371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/optimizely.rb', line 371

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.



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/optimizely.rb', line 422

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