Class: Rulix::Mutator

Inherits:
Base
  • Object
show all
Includes:
Registry
Defined in:
lib/rulix/mutator.rb

Class Method Summary collapse

Methods included from Registry

included

Methods inherited from Base

data_for_ruleset, handle_merge, value_from_dataset

Class Method Details

.reduce_into_hash(hash, dataset, ruleset) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rulix/mutator.rb', line 15

def self.reduce_into_hash hash, dataset, ruleset
  # Migrate over any keys the ruleset has that the dataset doesn't
  # so we can set defaults and handle cases where no data exists
  if dataset.respond_to? :keys
    key_diff = ruleset.keys - dataset.keys

    key_diff.each do |key|
      hash[key] = nil
    end
  end

  new_ruleset = ruleset.reduce(hash) do |data_hash, values|
    key, rule_val = values

    nested_value = value_from_dataset dataset, key

    if rule_val.is_a?(Hash) && (nested_value.is_a?(Hash) || rule_val.keys.all? { |k| nested_value.respond_to?(k) })
      seed = {}

      data_hash[key] = reduce_into_hash seed, nested_value, rule_val
    else
      data_hash[key] = nested_value
    end

    data_hash
  end

  # For mutation, we need to ensure that the resulting dataset
  # contains all original, unmodified values as well as mutated values
  if dataset.is_a? Hash
    new_ruleset.deep_merge dataset
  else
    new_ruleset
  end
end

.run(dataset, ruleset) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/rulix/mutator.rb', line 5

def self.run dataset, ruleset
  super dataset, ruleset do |value, operations|
    if value.is_a? Array
      value.map { |val| operations.reduce(val) { |v, op| op.call(v) } }
    else
      operations.reduce(value) { |val, op| op.call(val) }
    end
  end
end