This way we fix a bug we mentioned in commit 930bb753c which caused
links to documents to be broken when editing their title because the
title was used to generate the URL of the document.
Note we're still using Paperclip to render cached attachments because
this is the only case where we store files with just Paperclip and not
Active Storage.
With Active Storage, we render attachments just like any other resource,
using `polymorphic_path`. Paperclip included the `url` method in the
model; since the model doesn't have access to the request parameters
(like the host), this was inconvenient because it wasn't possible to
generate absolute URLs with Paperclip.
In order to simplify the code and make it similar to the way we used
Paperclip, we're adding a `variant` method accepting the name of a
variant and returning the variant.
71 lines
2.0 KiB
Ruby
71 lines
2.0 KiB
Ruby
class Attachable::FieldsComponent < ApplicationComponent
|
|
attr_reader :f, :resource_type, :resource_id, :relation_name
|
|
delegate :current_user, :render_image, to: :helpers
|
|
|
|
def initialize(f, resource_type:, resource_id:, relation_name:)
|
|
@f = f
|
|
@resource_type = resource_type
|
|
@resource_id = resource_id
|
|
@relation_name = relation_name
|
|
end
|
|
|
|
private
|
|
|
|
def attachable
|
|
f.object
|
|
end
|
|
|
|
def singular_name
|
|
attachable.model_name.singular
|
|
end
|
|
|
|
def plural_name
|
|
attachable.model_name.plural
|
|
end
|
|
|
|
def file_name
|
|
attachable.storage_attachment.filename if attachable.storage_attachment.attached?
|
|
end
|
|
|
|
def destroy_link
|
|
if !attachable.persisted? && attachable.cached_attachment.present?
|
|
link_to t("#{plural_name}.form.delete_button"), "#", class: "delete remove-cached-attachment"
|
|
else
|
|
link_to_remove_association remove_association_text, f, class: "delete remove-#{singular_name}"
|
|
end
|
|
end
|
|
|
|
def remove_association_text
|
|
if attachable.new_record?
|
|
t("documents.form.cancel_button")
|
|
else
|
|
t("#{plural_name}.form.delete_button")
|
|
end
|
|
end
|
|
|
|
def file_field
|
|
klass = attachable.persisted? || attachable.cached_attachment.present? ? " hide" : ""
|
|
f.file_field :attachment,
|
|
label_options: { class: "button hollow #{klass}" },
|
|
accept: accepted_content_types_extensions,
|
|
class: "js-#{singular_name}-attachment",
|
|
data: { url: direct_upload_path }
|
|
end
|
|
|
|
def direct_upload_path
|
|
direct_uploads_path("direct_upload[resource_type]": resource_type,
|
|
"direct_upload[resource_id]": resource_id,
|
|
"direct_upload[resource_relation]": relation_name)
|
|
end
|
|
|
|
def accepted_content_types_extensions
|
|
Setting.accepted_content_types_for(plural_name).map do |content_type|
|
|
if content_type == "jpg"
|
|
".jpg,.jpeg"
|
|
else
|
|
".#{content_type}"
|
|
end
|
|
end.join(",")
|
|
end
|
|
end
|