Files
nairobi/app/models/document.rb
Javi Martín e0e35298d5 Use Active Storage to handle cached attachments
This fixes a few issues we've had for years.

First, when attaching an image and then sending a form with validation
errors, the image preview would not be rendered when the form was
displayed once again. Now it's rendered as expected.

Second, when attaching an image, removing it, and attaching a new
one, browsers were displaying the image preview of the first one. That's
because Paperclip generated the same URL from both files (as they both
had the same hash data and prefix). Browsers usually cache images and
render the cached image when getting the same URL.

Since now we're storing each image in a different Blob, the images have
different URLs and so the preview of the second one is correctly
displayed.

Finally, when users downloaded a document, they were getting files with
a very long hexadecimal hash as filename. Now they get the original
filename.
2022-02-23 18:21:38 +01:00

58 lines
1.6 KiB
Ruby

class Document < ApplicationRecord
include Attachable
has_attachment :attachment, url: "/system/:class/:attachment/:id_partition/:style/:hash.:extension",
hash_data: ":class/:style/:custom_hash_data",
use_timestamp: false,
hash_secret: Rails.application.secrets.secret_key_base
belongs_to :user
belongs_to :documentable, polymorphic: true, touch: true
validates :title, presence: true
validates :user_id, presence: true
validates :documentable_id, presence: true, if: -> { persisted? }
validates :documentable_type, presence: true, if: -> { persisted? }
scope :admin, -> { where(admin: true) }
Paperclip.interpolates :custom_hash_data do |attachment, _style|
attachment.instance.custom_hash_data(attachment)
end
def self.humanized_accepted_content_types
Setting.accepted_content_types_for("documents").join(", ")
end
def custom_hash_data(attachment)
original_filename = if attachment.instance.persisted?
attachment.instance.title
else
attachment.instance.attachment_file_name
end
"#{attachment.instance.user_id}/#{original_filename}"
end
def humanized_content_type
attachment_content_type.split("/").last.upcase
end
def max_file_size
documentable_class.max_file_size
end
def accepted_content_types
documentable_class.accepted_content_types
end
private
def association_name
:documentable
end
def documentable_class
association_class
end
end