Permalink
Browse files

handle null values properly. refactoring

  • Loading branch information...
1 parent d68a22a commit dc3f52c9b49f11b12e072ccaffea13e4afe830c4 @twoism committed Mar 3, 2011
Showing with 15 additions and 10 deletions.
  1. +9 −9 lib/pathy.rb
  2. +6 −1 spec/lib/pathy_spec.rb
View
@@ -12,24 +12,24 @@ module InstanceMethods
# returns 'awesome'
def at_json_path path
method_chain = path.split('.')
- method_chain.inject(self.reparsed_as_json) do |obj,m|
- key = (obj.respond_to?(:push) ? m.to_i : m)
- new_value = obj.send('[]', key)
+ method_chain.inject(self.reparsed_as_json) do |obj,method|
- raise InvalidPathError, "Could not resolve #{path} at #{key}" if obj[key].nil?
+ 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)
- new_value
- end
- rescue
- raise InvalidPathError, "Could not resolve #{path}"
+ raise InvalidPathError, "Could not resolve #{path} at #{key_or_index}" unless has_key_or_index
+
+ obj.send('[]', key_or_index)
+ end
end
# returns true if the path is found. Provides usage in Rspec
# Example in rspec:
# {:some_key => {:nested_key => 'awesome'}}.should have_json_path('some_key.nested_key')
def has_json_path? path
begin
- self.at_json_path(path)
+ at_json_path(path)
true
rescue InvalidPathError
false
View
@@ -35,7 +35,8 @@
"number" : 1,
"array" : [1,2,3],
"hash" : {"one":{"two" : 2}},
- "bool" : false
+ "bool" : false,
+ "nullval" : null
}
]
@@ -90,6 +91,10 @@
it "should have 'bool'" do
@obj.should have_json_path 'bool'
end
+
+ it "should have 'nullval'" do
+ @obj.should have_json_path 'nullval'
+ end
it "should be false for invalid paths" do
@obj.has_json_path?('hash.one.does_not_exist').should be_false

0 comments on commit dc3f52c

Please sign in to comment.