Module: HashPath

Included in:
Hash
Defined in:
lib/hash_path.rb,
lib/hash_path/version.rb

Defined Under Namespace

Classes: PathNotFound

Constant Summary collapse

DELIMITER =
'.'
VERSION =
"0.3.0"

Instance Method Summary collapse

Instance Method Details

#at_path(path) ⇒ Object

Looks up the path provided

Examples:

my_hash.at_path("foo.bar.baz") # looks in my_hash['foo']['bar']['baz']

Parameters:

  • path

    String the path to lookup



11
12
13
14
15
16
17
18
19
20
# File 'lib/hash_path.rb', line 11

def at_path(path)
  path_keys = normalize_path(path)
  current_value = self

  path_keys.each do |key|
    return nil unless current_value.respond_to?(:[])
    current_value = current_value[key]
  end
  current_value
end

#at_path!(path) ⇒ Object

Same as at_path but raises when a path is not found The raise will give a delimited path of where the path went dead

Examples:

f = { 'foo' => {'bar' => {'baz' => 'hai'}, "baz" => [1,2] } }
f.at_path!('foo.not.baz') # Raises, message == 'foo.not'
f.at_path!('not.here.yo') # Raises, message == 'not'
f.at_path!('foo.bar.not') # Raises, message == 'foo.bar.not'
f.at_path!("baz.1") # => 2

See Also:



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/hash_path.rb', line 31

def at_path!(path)
  path_keys = normalize_path(path)
  the_keys, current_value = [], self

  path_keys.each do |key|
    raise(PathNotFound, the_keys.join(DELIMITER)) unless current_value.respond_to?(:[])
    the_keys << key
    current_value = current_value[key]
  end
  current_value
end

#flatten_key_paths(hash_or_obj = self, prefix = nil) ⇒ Object

Provides flattened hash key paths



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hash_path.rb', line 44

def flatten_key_paths(hash_or_obj=self, prefix=nil)
  case hash_or_obj
  when Hash
    hash_or_obj.inject({}) do |h, (k,v)|
      full_prefix = [prefix, k].compact.join(".")
      result = flatten_key_paths(v, full_prefix)
      if Hash === result
        h.merge! result
      else
        h[full_prefix] = result
      end
      h
    end
  else
    hash_or_obj
  end
end