Class: CustomStrategyHandler

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

Instance Method Summary collapse

Constructor Details

#initializeCustomStrategyHandler

Returns a new instance of CustomStrategyHandler.



12
13
14
15
# File 'lib/custom_strategy.rb', line 12

def initialize
  @custom_strategies_definitions = {}
  @custom_strategy_implementations = {}
end

Instance Method Details

#evaluate_custom_strategies(toggle_name, context) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/custom_strategy.rb', line 50

def evaluate_custom_strategies(toggle_name, context)
  results = {}

  @custom_strategies_definitions[toggle_name]&.each_with_index do |strategy, index|
    key = "customStrategy#{index + 1}"
    strategy_impl = @custom_strategy_implementations[strategy["name"]]
    result = strategy_impl&.enabled?(strategy["parameters"], context) || false
    results[key] = result
  end

  results
end

#register_custom_strategies(strategies) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/custom_strategy.rb', line 39

def register_custom_strategies(strategies)
  strategies.each do |strategy|
    if strategy.respond_to?(:name) && strategy.name.is_a?(String) &&
       strategy.respond_to?(:enabled?)
      @custom_strategy_implementations[strategy.name] = strategy
    else
      raise "Invalid strategy object. Must have a name method that returns a String and an enabled? method."
    end
  end
end

#update_strategies(json_str) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/custom_strategy.rb', line 17

def update_strategies(json_str)
  custom_strategies = {}
  parsed_json = JSON.parse(json_str)

  features = extract_features parsed_json

  features.each do |feature|
    toggle_name = feature["name"]
    strategies = feature["strategies"]

    custom_strategies_for_toggle = strategies.select do |strategy|
      !STANDARD_STRATEGIES.include?(strategy["name"])
    end

    unless custom_strategies_for_toggle.empty?
      custom_strategies[toggle_name] = custom_strategies_for_toggle
    end
  end

  @custom_strategies_definitions = custom_strategies
end