Permalink
Browse files

Fixing destroy callback to delete files just when model destroy metho…

…d was completed successfully (i.e. no exception like 'foreign key constraint violations' was raised)
  • Loading branch information...
1 parent aee47d8 commit 472a625a1eca8b157cbc531f59dd27dd99b62194 @mariopeixoto mariopeixoto committed Aug 26, 2011
Showing with 38 additions and 2 deletions.
  1. +10 −2 lib/paperclip.rb
  2. +28 −0 test/attachment_test.rb
View
@@ -271,7 +271,8 @@ def has_attached_file name, options = {}
attachment_definitions[name] = {:validations => []}.merge(options)
after_save :save_attached_files
- before_destroy :destroy_attached_files
+ before_destroy :prepare_for_destroy
+ after_destroy :destroy_attached_files
define_paperclip_callbacks :post_process, :"#{name}_post_process"
@@ -407,10 +408,17 @@ def save_attached_files
def destroy_attached_files
Paperclip.log("Deleting attachments.")
each_attachment do |name, attachment|
- attachment.send(:queue_existing_for_delete)
attachment.send(:flush_deletes)
end
end
+
+ def prepare_for_destroy
+ Paperclip.log("Scheduling attachments for deletion.")
+ each_attachment do |name, attachment|
+ attachment.send(:queue_existing_for_delete)
+ end
+ end
+
end
end
View
@@ -1076,4 +1076,32 @@ def self.interpolate(pattern, attachment, style_name)
assert_equal "hello", attachment.url
end
end
+
+ context "An attached file" do
+ setup do
+ rebuild_model
+ @dummy = Dummy.new
+ @file = File.new(File.join(File.dirname(__FILE__), "fixtures", "5k.png"), 'rb')
+ @dummy.avatar = @file
+ @dummy.save!
+ @attachment = @dummy.avatar
+ @path = @attachment.path
+ end
+
+ should "not be deleted when the model fails to destroy" do
+ @dummy.stubs(:destroy).raises(Exception)
+
+ assert_raise Exception do
+ @dummy.destroy
+ end
+
+ assert File.exists?(@path)
+ end
+
+ should "be deleted when the model is destroyed" do
+ @dummy.destroy
+ assert ! File.exists?(@path)
+ end
+ end
+
end

0 comments on commit 472a625

Please sign in to comment.