Skip to content
Browse files

Merge pull request #30 from dylanahsmith/persist-nested

Mark nested resources as persisted when loaded from a response.
  • Loading branch information...
2 parents 6639bb4 + cb60edc commit 8f6a8b37b39a1712ee43a12e17664d1c86a3d685 @jeremy jeremy committed Oct 19, 2012
Showing with 19 additions and 6 deletions.
  1. +6 −6 lib/active_resource/base.rb
  2. +13 −0 test/cases/base_test.rb
View
12 lib/active_resource/base.rb
@@ -1055,7 +1055,7 @@ def initialize(attributes = {}, persisted = false)
@attributes = {}.with_indifferent_access
@prefix_options = {}
@persisted = persisted
- load(attributes)
+ load(attributes, false, persisted)
end
# Returns a \clone of the resource that hasn't been assigned an +id+ yet and
@@ -1283,7 +1283,7 @@ def encode(options={})
# my_branch.reload
# my_branch.name # => "Wilson Road"
def reload
- self.load(self.class.find(to_param, :params => @prefix_options).attributes)
+ self.load(self.class.find(to_param, :params => @prefix_options).attributes, false, true)
end
# A method to manually load attributes from a \hash. Recursively loads collections of
@@ -1307,7 +1307,7 @@ def reload
# your_supplier = Supplier.new
# your_supplier.load(my_attrs)
# your_supplier.save
- def load(attributes, remove_root = false)
+ def load(attributes, remove_root = false, persisted = false)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
@prefix_options, attributes = split_options(attributes)
@@ -1325,14 +1325,14 @@ def load(attributes, remove_root = false)
value.map do |attrs|
if attrs.is_a?(Hash)
resource ||= find_or_create_resource_for_collection(key)
- resource.new(attrs)
+ resource.new(attrs, persisted)
else
attrs.duplicable? ? attrs.dup : attrs
end
end
when Hash
resource = find_or_create_resource_for(key)
- resource.new(value)
+ resource.new(value, persisted)
else
value.duplicable? ? value.dup : value
end
@@ -1427,7 +1427,7 @@ def load_attributes_from_response(response)
if (response_code_allows_body?(response.code) &&
(response['Content-Length'].nil? || response['Content-Length'] != "0") &&
!response.body.nil? && response.body.strip.size > 0)
- load(self.class.format.decode(response.body), true)
+ load(self.class.format.decode(response.body), true, true)
@persisted = true
end
end
View
13 test/cases/base_test.rb
@@ -1147,6 +1147,19 @@ def test_parse_deep_nested_resources
end
end
+ def test_persisted_nested_resources_from_response
+ luis = Customer.find(1)
+ luis.friends.each do |friend|
+ assert !friend.new?
+ friend.brothers.each do |brother|
+ assert !brother.new?
+ brother.children.each do |child|
+ assert !child.new?
+ end
+ end
+ end
+ end
+
def test_parse_resource_with_given_has_one_resources
Customer.send(:has_one, :mother, :class_name => "external/person")
luis = Customer.find(1)

0 comments on commit 8f6a8b3

Please sign in to comment.
Something went wrong with that request. Please try again.