Skip to content

Commit

Permalink
- ActiveResource added clear method to has_many association
Browse files Browse the repository at this point in the history
  • Loading branch information
gramos committed Oct 6, 2010
1 parent 9c3e20f commit 3666989
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
20 changes: 13 additions & 7 deletions activeresource/lib/active_resource/associations.rb
Expand Up @@ -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}")
Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand Down
8 changes: 8 additions & 0 deletions activeresource/test/cases/associations_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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.