From 0cf5fbe3111baf9a6bdeac69ff4e5ab4ed9bf935 Mon Sep 17 00:00:00 2001 From: "Jonathan S. Katz" Date: Wed, 29 Oct 2008 23:56:10 -0400 Subject: [PATCH] added #has_attachment? method --- lib/couchrest/core/model.rb | 8 ++++++-- spec/couchrest/core/model_spec.rb | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/lib/couchrest/core/model.rb b/lib/couchrest/core/model.rb index 7221d6d..aebdbb1 100644 --- a/lib/couchrest/core/model.rb +++ b/lib/couchrest/core/model.rb @@ -507,7 +507,7 @@ module CouchRest # creates a file attachment to the current doc def create_attachment(file, attachment_name) - return if self['_attachments'] && self['_attachments'][attachment_name] && !self['_attachments'][attachment_name].empty? + return if has_attachment?(attachment_name) self['_attachments'] ||= {} set_attachment_attr(file, attachment_name) end @@ -519,7 +519,7 @@ module CouchRest # modifies a file attachment on the current doc def update_attachment(file, attachment_name) - return unless self['_attachments'] && self['_attachments'][attachment_name] + return unless has_attachment?(attachment_name) delete_attachment(attachment_name) set_attachment_attr(file, attachment_name) end @@ -529,6 +529,10 @@ module CouchRest return unless self['_attachments'] self['_attachments'].delete attachment_name end + + def has_attachment?(attachment_name) + !!(self['_attachments'] && self['_attachments'][attachment_name] && !self['_attachments'][attachment_name].empty?) + end protected diff --git a/spec/couchrest/core/model_spec.rb b/spec/couchrest/core/model_spec.rb index 2ac80c5..7ccbe4d 100644 --- a/spec/couchrest/core/model_spec.rb +++ b/spec/couchrest/core/model_spec.rb @@ -728,6 +728,35 @@ describe CouchRest::Model do end end + describe "#has_attachment?" do + before(:each) do + @obj = Basic.new + @obj.save.should == true + @file = File.open(FIXTURE_PATH + '/attachments/test.html') + @attachment_name = 'my_attachment' + @obj.create_attachment(@file, @attachment_name) + end + + it 'should return false if there is no attachment' do + @obj.has_attachment?('bogus').should be_false + end + + it 'should return true if there is an attachment' do + @obj.has_attachment?(@attachment_name).should be_true + end + + it 'should return true if an object with an attachment is reloaded' do + @obj.save.should be_true + reloaded_obj = Basic.get(@obj.id) + reloaded_obj.has_attachment?(@attachment_name).should be_true + end + + it 'should return false if an attachment has been removed' do + @obj.delete_attachment(@attachment_name) + @obj.has_attachment?(@attachment_name).should be_false + end + end + describe "creating an attachment" do before(:each) do @obj = Basic.new