Skip to content
Permalink
Browse files

Allow selectively purging attached blobs

  • Loading branch information...
nicholasshirley authored and georgeclaghorn committed Feb 12, 2018
1 parent 40d3fa5 commit f9a5839083e697f0d5aad6d9304cd5f26e2a7a11
@@ -85,7 +85,17 @@ def #{name}=(attachables)
end
CODE

has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record, dependent: false
has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record, dependent: false do
def purge
each(&:purge)
reset
end

def purge_later
each(&:purge_later)
reset
end
end
has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "ActiveStorage::Blob", source: :blob

scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) }
@@ -44,20 +44,16 @@ def detach
attachments.destroy_all if attached?
end

##
# :method: purge
#
# Directly purges each associated attachment (i.e. destroys the blobs and
# attachments and deletes the files on the service).
def purge
if attached?
attachments.each(&:purge)
attachments.reload
end
end


##
# :method: purge_later
#
# Purges each associated attachment through the queuing system.
def purge_later
if attached?
attachments.each(&:purge_later)
end
end
end
end
@@ -418,4 +418,32 @@ class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
@user.destroy
assert_not ActiveStorage::Attachment.exists?(record: @user, name: "vlogs")
end

test "selectively purge one attached blob of many" do
first_blob = create_blob(filename: "funky.jpg")
second_blob = create_blob(filename: "wonky.jpg")
attachments = @user.highlights.attach(first_blob, second_blob)

assert_difference -> { ActiveStorage::Blob.count }, -1 do
@user.highlights.where(id: attachments.first.id).purge
end

assert_not ActiveStorage::Blob.exists?(key: first_blob.key)
assert ActiveStorage::Blob.exists?(key: second_blob.key)
end

test "selectively purge one attached blob of many later" do
first_blob = create_blob(filename: "funky.jpg")
second_blob = create_blob(filename: "wonky.jpg")
attachments = @user.highlights.attach(first_blob, second_blob)

perform_enqueued_jobs do
assert_difference -> { ActiveStorage::Blob.count }, -1 do
@user.highlights.where(id: attachments.first.id).purge_later
end
end

assert_not ActiveStorage::Blob.exists?(key: first_blob.key)
assert ActiveStorage::Blob.exists?(key: second_blob.key)
end
end

0 comments on commit f9a5839

Please sign in to comment.
You can’t perform that action at this time.