Module: Attrify::Helpers

Included in:
Attrify, OperationSet, Parser, Variant, VariantRegistry
Defined in:
lib/attrify/helpers.rb

Instance Method Summary collapse

Instance Method Details

#compute_attributes(hash) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/attrify/helpers.rb', line 5

def compute_attributes(hash)
  results = {}

  hash.each do |key, operations|
    if operations.is_a?(Hash)
      results[key] = compute_attributes(operations)
    elsif operations.is_a?(Array)
      current_value = []

      # Process each operation in order
      operations.each do |operation_hash|
        operation_hash.each do |operation, value|
          current_value = execute_operation(operation.to_sym, current_value, value)
        end
      end

      # Flatten array and convert to string if not a hash
      results[key] = current_value.join(" ")
    else
      results[key] = operations
    end
  end

  results
end

#deep_merge_hashes(hash1, hash2) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/attrify/helpers.rb', line 58

def deep_merge_hashes(hash1, hash2)
  hash1.merge(hash2) do |key, oldval, newval|
    if oldval.is_a?(Hash)
      deep_merge_hashes(oldval, newval)
    elsif oldval.is_a?(Array)
      oldval + newval  # Concatenate arrays
    else
      newval
    end
  end
end

#deep_merge_hashes!(hash1, hash2) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/attrify/helpers.rb', line 46

def deep_merge_hashes!(hash1, hash2)
  hash1.merge!(hash2) do |key, oldval, newval|
    if oldval.is_a?(Hash)
      deep_merge_hashes(oldval, newval)
    elsif oldval.is_a?(Array)
      oldval + newval  # Concatenate arrays
    else
      newval  # In case of conflicting types or non-container types, prefer newval
    end
  end
end

#execute_operation(operation, current_value, value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/attrify/helpers.rb', line 31

def execute_operation(operation, current_value, value)
  case operation
  when :append
    current_value + value
  when :prepend
    value + current_value
  when :remove
    current_value - value
  when :set
    value
  else
    current_value
  end
end