Files
nairobi/app/components/documents/fields_component.rb
Javi Martín 930bb753c5 Use a rake task to delete cached attachments
Our previous system to delete cached attachments didn't work for
documents because the `custom_hash_data` is different for files created
from a file and files created from cached attachments.

When creating a document attachment, the name of the file is taken into
account to calculate the hash. Let's say the original file name is
"logo.pdf", and the generated hash is "123456". The cached attachment
will be "123456.pdf", so the generated hash using the cached attachment
will be something different, like "28af3". So the file that will be
removed will be "28af3.pdf", and not "123456.pdf", which will still be
present.

Furthermore, there are times where users choose a file and then they
close the browser or go to a different page. In those cases, we weren't
deleting the cached attachments either.

So we're adding a rake task to delete these files once a day. This way
we can simplify the logic we were using to destroy cached attachments.

Note there's related a bug in documents: when editing a record (for
example, a proposal), if the title of the document changes, its hash
changes, and so it will be impossible to generate a link to that
document. Changing the way this hash is generated is not an option
because it would break links to existing files. We'll try to fix it when
moving to Active Storage.
2021-07-30 17:30:11 +02:00

46 lines
1.4 KiB
Ruby

class Documents::FieldsComponent < ApplicationComponent
attr_reader :f
delegate :current_user, to: :helpers
def initialize(f)
@f = f
end
private
def document
f.object
end
def file_name
document.attachment_file_name
end
def destroy_link
if !document.persisted? && document.cached_attachment.present?
link_to t("documents.form.delete_button"), "#", class: "delete remove-cached-attachment"
else
link_to_remove_association document.new_record? ? t("documents.form.cancel_button") : t("documents.form.delete_button"), f, class: "delete remove-document"
end
end
def file_field
klass = document.persisted? || document.cached_attachment.present? ? " hide" : ""
f.file_field :attachment,
label_options: { class: "button hollow #{klass}" },
accept: accepted_content_types_extensions,
class: "js-document-attachment",
data: { url: direct_upload_path }
end
def direct_upload_path
direct_uploads_path("direct_upload[resource_type]": document.documentable_type,
"direct_upload[resource_id]": document.documentable_id,
"direct_upload[resource_relation]": "documents")
end
def accepted_content_types_extensions
Setting.accepted_content_types_for("documents").map { |content_type| ".#{content_type}" }.join(",")
end
end