Module: Traipse
- Defined in:
- lib/traipse.rb,
lib/traipse/version.rb
Constant Summary collapse
- SEPARATOR =
'.'
- VERSION =
"0.6.0"
Class Method Summary collapse
-
._find(object, path, results = []) ⇒ Object
:nodoc:.
-
._find_with_keys(object, path, full_path = [], results = {}) ⇒ Object
:nodoc:.
-
.find(object, path) ⇒ Object
Find a needle in a haystack using something akin to JSON dot syntax ex: Traipse.find( data, ‘cat.name’ ) # similar to data[‘name’].
- .find_with_keys(object, path) ⇒ Object
Class Method Details
._find(object, path, results = []) ⇒ Object
:nodoc:
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/traipse.rb', line 17 def self._find( object, path, results=[] ) # :nodoc: key, *rest = path # Oops.. no key? Hands a path of '*' return [ object ] unless key # What happens if we miss a key? return [] unless object.is_a?( Hash ) # Handle wildcard hash keys if key == '*' object.keys.each do |subkey| results += _find( object, [ subkey, *rest ] ) end return results end # This is the end of the line, megatron. return [ object[ key ] ].compact if rest.empty? # Traverse hashes and arrays case object[ key ] when Hash return _find( object[ key ], rest ) when Array object[ key ].each do |obj| results += _find( obj, rest ) end end return results end |
._find_with_keys(object, path, full_path = [], results = {}) ⇒ Object
:nodoc:
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/traipse.rb', line 50 def self._find_with_keys( object, path, full_path=[], results={} ) # :nodoc: key, *rest = path full_path << key unless key == "*" # Handle wildcard hash keys if key == '*' object.keys.each do |subkey| results.merge! _find_with_keys( object, [ subkey, *rest ], full_path.dup ) end return results.reject { |k,v| v.nil? } end # This is the end of the line, megatron. return { full_path.join(".") => object[key] } if rest.empty? # Traverse hashes and arrays case object[ key ] when Hash return _find_with_keys( object[ key ], rest, full_path ) when Array if rest.first =~ /^\d+$/ index = rest.shift.to_i results.merge! _find_with_keys( object[key][index], rest, full_path + [index] ) else object[ key ].each_with_index do |obj, index| results.merge! _find_with_keys( obj, rest, full_path + [index] ) end end end return results end |
.find(object, path) ⇒ Object
Find a needle in a haystack using something akin to JSON dot syntax ex: Traipse.find( data, ‘cat.name’ ) # similar to data[‘name’]
9 10 11 |
# File 'lib/traipse.rb', line 9 def self.find( object, path ) return _find( object, path.split( SEPARATOR ) ) end |
.find_with_keys(object, path) ⇒ Object
13 14 15 |
# File 'lib/traipse.rb', line 13 def self.find_with_keys( object, path ) _find_with_keys( object, path.split( SEPARATOR ) ) end |