Class: HashPath

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ HashPath

Returns a new instance of HashPath.



29
30
31
32
# File 'lib/hash-path.rb', line 29

def initialize(hash = {})
  super()
  replace(hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)



35
36
37
38
39
40
41
# File 'lib/hash-path.rb', line 35

def method_missing(name, *args, &block)
  if args.empty?
    self[ self.class.paths[name.to_s] || name ]
  else
    super
  end
end

Class Method Details

.path(key, path) ⇒ Object



7
8
9
# File 'lib/hash-path.rb', line 7

def path(key, path)
  paths[key.to_s] = path
end

.pathsObject



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

def paths
  @paths ||= {}
end

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  key = key.to_s

  if (key[0,1] == '$') && defined?(JsonPath)
    # jsonpath
    @jsonpath ||= JsonPath.wrap(self)
    return @jsonpath.path(key).to_a

  else
    # first, check if key has '/'
    return super unless key.index('/')

    # second, browse children
    return key.split("/").inject(self) {|hash, k| hash ? hash[k] : nil}
  end
end