Module: Pathy::InstanceMethods
- Defined in:
- lib/pathy.rb
Instance Method Summary collapse
-
#at_json_path(path) ⇒ Object
returns the value parsed from JSON at a given path.
-
#has_json_path?(path) ⇒ Boolean
returns true if the path is found.
-
#reparsed_as_json ⇒ Object
returns the parsed JSON representation of an instance.
Instance Method Details
#at_json_path(path) ⇒ Object
returns the value parsed from JSON at a given path. Example: => {:nested_key => ‘awesome’}.at_json_path(‘some_key.nested_key’) returns ‘awesome’
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/pathy.rb', line 13 def at_json_path path method_chain = path.split('.') method_chain.inject(self.reparsed_as_json) do |obj,method| is_array_like = obj.respond_to?(:push) key_or_index = is_array_like ? method.to_i : method has_key_or_index = is_array_like ? !obj.slice(key_or_index).nil? : obj.keys.include?(key_or_index) raise InvalidPathError, "Could not resolve #{path} at #{key_or_index}" unless has_key_or_index obj.send('[]', key_or_index) end end |
#has_json_path?(path) ⇒ Boolean
returns true if the path is found. Provides usage in Rspec Example in rspec: => {:nested_key => ‘awesome’}.should have_json_path(‘some_key.nested_key’)
30 31 32 33 34 35 36 37 |
# File 'lib/pathy.rb', line 30 def has_json_path? path begin at_json_path(path) true rescue InvalidPathError false end end |
#reparsed_as_json ⇒ Object
returns the parsed JSON representation of an instance. If the current instance is a string we assume it’s JSON
41 42 43 |
# File 'lib/pathy.rb', line 41 def reparsed_as_json self.is_a?(String) ? JSON.parse(self) : JSON.parse(self.to_json) end |