Permalink
Browse files

- ActiveResource added clear method to has_many association

  • Loading branch information...
1 parent 9c3e20f commit 36669894cbc48985e4eb12e27fbc18431af79df9 @gramos committed Oct 1, 2010
@@ -8,8 +8,7 @@ def self.included(klass)
module InstanceMethods
def set_resource_instance_variable(resource, default_value = nil)
- if !instance_variable_defined?("@#{resource}") ||
- instance_variable_get("@#{resource}").blank?
+ if !instance_variable_defined?("@#{resource}")
instance_variable_set("@#{resource}", yield)
end
instance_variable_get("@#{resource}")
@@ -112,8 +111,11 @@ def has_many(resource, opts = {})
#
#----------------------------------------------------------------------#
define_method(resource) do
- collection = o[:klass].constantize.find(:all,
- :params => { o[:association_col] => id })
+
+ collection = set_resource_instance_variable(resource) {
+ o[:klass].constantize.find(:all,
+ :params => { o[:association_col] => id }) || []
+ }
instance_eval "
def collection.<<(member)
@@ -125,11 +127,15 @@ def collection.<<(member)
def collection.delete(member)
member.#{o[:association_col]} = nil
member.save
+ super(member)
end"
- set_resource_instance_variable(resource) do
- collection
- end
+ instance_eval "
+ def collection.clear
+ self.each{|member| delete(member)}
+ end"
+
+ collection
end
end
@@ -37,6 +37,7 @@ class Milestone < ActiveResource::Base
mock.get "/milestones.xml?project_id=1", {}, [@milestone].to_xml
mock.put "/project_managers/6.xml", {}, nil, 204
mock.put "/milestones/2.xml", {}, nil, 204
+ mock.put "/milestones/1.xml", {}, nil, 204
mock.get "/milestones/1.xml", {}, @milestone.to_xml(:root => 'milestone')
mock.get "/milestones/2.xml", {}, @other_milestone.to_xml(:root => 'milestone')
end
@@ -120,5 +121,12 @@ def test_has_many_accessor_should_return_the_an_array_without_including_the_dele
@project.milestones.delete(@other_milestone)
assert_nil @other_milestone.project_id
end
+
+ def test_has_many_accessor_should_return_the_an_empty_array_after_clear
+ @project.milestones << @other_milestone
+ @project.milestones.clear
+
+ assert_equal [], @project.milestones
+ end
end

0 comments on commit 3666989

Please sign in to comment.