Class: Dotpath::Mutate

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

Class Method Summary collapse

Class Method Details

.array(obj, path: DELIMITER, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dotpath/mutate.rb', line 32

def self.array(obj, path: DELIMITER, &block)
  new_array = []
  index = 0
  obj.each do |value|
    new_path = "#{path}[#{index}]"
    case value
    when Hash
      new_array << hash(value, path: new_path, &block)
    when Array
      new_array << array(value, path: new_path, &block)
    else
      new_array << yield(new_path, value)
    end

    index += 1
  end
  new_array
end

.hash(obj, path: DELIMITER, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/dotpath/mutate.rb', line 16

def self.hash(obj, path: DELIMITER, &block)
  new_hash = {}
  obj.each do |key, value|
    new_path = [path, key].join(DELIMITER)
    case value
    when Hash
      new_hash[key] = hash(value, path: new_path, &block)
    when Array
      new_hash[key] = array(value, path: new_path, &block)
    else
      new_hash[key] = yield(new_path, value)
    end
  end
  new_hash
end

.mutate(obj, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/dotpath/mutate.rb', line 5

def self.mutate(obj, &block)
  case obj
  when Hash
    hash(obj, path: '', &block)
  when Array
    array(obj, &block)
  else
    obj
  end
end