Class: HashJsonPath

Inherits:
Object
  • Object
show all
Defined in:
lib/hash-json-path.rb

Constant Summary collapse

SEPERATOR_REGEX =

e.g. local_results[1] => [“local_results”, “0”, “1”]

/[^\[|^\]]+/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, separator_regex = SEPERATOR_REGEX) ⇒ HashJsonPath

Returns a new instance of HashJsonPath.



8
9
10
11
# File 'lib/hash-json-path.rb', line 8

def initialize(hash, separator_regex = SEPERATOR_REGEX)
  @hash = hash
  @separator_regex = separator_regex
end

Class Method Details

.on(hash) ⇒ Object



4
5
6
# File 'lib/hash-json-path.rb', line 4

def self.on(hash)
  new(hash)
end

Instance Method Details

#get(path) ⇒ Object



22
23
24
# File 'lib/hash-json-path.rb', line 22

def get(path)
  @hash.dig(*access_keys(path))
end

#merge(path, hash_value) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/hash-json-path.rb', line 39

def merge(path, hash_value)
  raise "Empty path is not allowed" if path.nil? || path.empty?
  raise "Value must be a Hash" unless hash_value.is_a?(Hash)

  *ancestors, leaf = access_keys(path)
  tampered_hash = ancestors.empty? ? @hash : @hash.dig(*ancestors)
  raise "Trying to merge a non hash value" unless tampered_hash[leaf].is_a?(Hash)
  tampered_hash[leaf] = tampered_hash[leaf].merge(hash_value)
  self
end

#prepend(path, hash_value) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/hash-json-path.rb', line 50

def prepend(path, hash_value)
  raise "Empty path is not allowed" if path.nil? || path.empty?
  raise "Value must be a Hash" unless hash_value.is_a?(Hash)

  *ancestors, leaf = access_keys(path)
  tampered_hash = ancestors.empty? ? @hash : @hash.dig(*ancestors)
  raise "Trying to merge with a non hash value" unless tampered_hash[leaf].is_a?(Hash)
  tampered_hash[leaf] = hash_value.merge(tampered_hash[leaf])
  self
end

#safe_get(path) ⇒ Object



26
27
28
# File 'lib/hash-json-path.rb', line 26

def safe_get(path)
  get(@hash, path) rescue nil
end

#set(path, value) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/hash-json-path.rb', line 30

def set(path, value)
  raise "Empty path is not allowed" if path.nil? || path.empty?

  *ancestors, leaf = access_keys(path)
  tampered_hash = ancestors.empty? ? @hash : @hash.dig(*ancestors)
  tampered_hash[leaf] = value
  self
end

#use_separator_regex(separator_regex) ⇒ Object



13
14
15
16
# File 'lib/hash-json-path.rb', line 13

def use_separator_regex(separator_regex)
  @separator_regex = separator_regex
  self
end

#valueObject



18
19
20
# File 'lib/hash-json-path.rb', line 18

def value
  @hash
end