Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
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...
commit 472a625a1eca8b157cbc531f59dd27dd99b62194 1 parent aee47d8
@mariopeixoto mariopeixoto authored
Showing with 38 additions and 2 deletions.
  1. +10 −2 lib/paperclip.rb
  2. +28 −0 test/attachment_test.rb
View
12 lib/paperclip.rb
@@ -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
28 test/attachment_test.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.