Module: HashPath
- Included in:
- Hash
- Defined in:
- lib/hash_path.rb,
lib/hash_path/version.rb
Defined Under Namespace
Modules: NilPath Classes: PathNotFound
Constant Summary collapse
- DELIMITER =
'.'
- VERSION =
"0.5.0"
Instance Method Summary collapse
-
#at_path(path) ⇒ Object
Looks up the path provided.
-
#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.
-
#flatten_key_paths(hash_or_obj = self, prefix = nil) ⇒ Object
Provides flattened hash key paths.
Instance Method Details
#at_path(path) ⇒ Object
Looks up the path provided
27 28 29 |
# File 'lib/hash_path.rb', line 27 def at_path(path) at_path!(path) rescue nil 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
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/hash_path.rb', line 40 def at_path!(path) the_keys = [] normalize_path(path).reduce(self) do |memo, key| the_keys << key case key when String memo.key?(key) ? memo.fetch(key) : memo.fetch(key.to_sym) else memo.fetch(key) end end rescue => e raise(PathNotFound, the_keys.join(DELIMITER)) end |
#flatten_key_paths(hash_or_obj = self, prefix = nil) ⇒ Object
Provides flattened hash key paths
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/hash_path.rb', line 58 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(DELIMITER) result = flatten_key_paths(v, full_prefix) case result when Hash h.merge!(result) else h[full_prefix] = result end h end else hash_or_obj end end |