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
-
#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
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
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 |