Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/karist/patch/hash.rb

Instance Method Summary collapse

Instance Method Details

#_concat(mutations) ⇒ Object

{items: [a, b], sep: sep} = a`sep`b



36
37
38
39
40
41
42
43
# File 'lib/karist/patch/hash.rb', line 36

def _concat(mutations)
  if self.key?(:_concat)
    case self[:_concat]
    in {items: items, sep: sep}
      return items.mutate(mutations).join(sep)
    end
  end
end

#_deep_transform_keys_in_object(object, &block) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/karist/patch/hash.rb', line 60

def _deep_transform_keys_in_object(object, &block)
  case object
  when Hash
    object.each_with_object(self.class.new) do |(key, value), result|
      result[yield(key)] = _deep_transform_keys_in_object(value, &block)
    end
  when Array
    object.map { |e| _deep_transform_keys_in_object(e, &block) }
  else
    object
  end
end

#_merge(mutations) ⇒ Object

{ _merge: x, **} = x



26
27
28
29
30
31
32
33
# File 'lib/karist/patch/hash.rb', line 26

def _merge(mutations)
  if self.key?(:_merge)
    self.merge!(mutations.dig_str(self[:_merge], mutations))
    self.delete(:_merge)
  end

  self
end

#_sum(mutations) ⇒ Object

{ _sum: [x, y, z]} = x + (y + z)



17
18
19
20
21
22
23
# File 'lib/karist/patch/hash.rb', line 17

def _sum(mutations)
  if self.key?(:_sum)
    return [self[:_sum].map{|el| el.mutate(mutations)}.sum, true]
  end

  self
end

#deep_stringify_keysObject



73
74
75
# File 'lib/karist/patch/hash.rb', line 73

def deep_stringify_keys
  deep_transform_keys(&:to_s)
end

#deep_symbolize_keysObject



52
53
54
# File 'lib/karist/patch/hash.rb', line 52

def deep_symbolize_keys
  deep_transform_keys { |key| key.to_sym rescue key }
end

#deep_transform_keys(&block) ⇒ Object



56
57
58
# File 'lib/karist/patch/hash.rb', line 56

def deep_transform_keys(&block)
  _deep_transform_keys_in_object(self, &block)
end

#dig_str(str, mutations) ⇒ Object



45
46
47
# File 'lib/karist/patch/hash.rb', line 45

def dig_str(str, mutations)
  self.dig(*str.split(".").map{|k| k.to_sym}).mutate(mutations)
end

#mutate(mutations) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/karist/patch/hash.rb', line 2

def mutate(mutations)
  _merge(mutations)

  sum_result = _sum(mutations)
  return sum_result[0] if sum_result[1]
  
  concat = _concat(mutations)
  if concat.is_a?(String)
    return concat
  end

  self.each {|a, z| self[a] = z.mutate(mutations)}
end