Class: Volt::DataTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/volt/utils/data_transformer.rb

Class Method Summary collapse

Class Method Details

.transform(data, &block) ⇒ Object

Takes a hash or array, and nested map’s over the values, yielding to the block the value. The return value from the block replaces the previous value. NOTE: This does not yield hashes or arrays.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/volt/utils/data_transformer.rb', line 12

def self.transform(data, &block)
  if data.is_a?(Hash)
    data.map do |key, value|
      key = transform(key, &block)
      value = transform(value, &block)
      [key, value]
    end.to_h
  elsif data.is_a?(Array)
    data.map do |value|
      transform(value, &block)
    end
  else
    # yield to the trasnformer
    yield(data)
  end
end

.transform_keys(data, &block) ⇒ Object

Like #transform, except it only yields keys.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/volt/utils/data_transformer.rb', line 30

def self.transform_keys(data, &block)
  if data.is_a?(Hash)
    data.map do |key, value|
      key = transform_keys(key, &block)
      value = transform_keys(value, &block)

      # map the key
      [yield(key), value]
    end.to_h
  elsif data.is_a?(Array)
    data.map do |value|
      transform_keys(value, &block)
    end
  else
    # no mapping
    data
  end
end