Skip to content

Commit

Permalink
Move format validator check to application helper
Browse files Browse the repository at this point in the history
  • Loading branch information
B-Rass committed Oct 29, 2024
1 parent 58ecb1e commit 9453d21
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 20 deletions.
9 changes: 9 additions & 0 deletions app/helpers/application_helper.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
# frozen_string_literal: true

module ApplicationHelper
def accepted_format_for_attachment(model_klass, attribute_name)
validator = model_klass.validators_on(attribute_name.to_sym).find do |v|
v.is_a?(ActiveStorageValidations::ContentTypeValidator)
end

return unless validator

validator.options[:in].map { |f| Mime[f].to_s }.uniq.join(", ")
end
end
10 changes: 0 additions & 10 deletions app/helpers/sites_helper.rb

This file was deleted.

2 changes: 1 addition & 1 deletion app/views/sites/_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
<%= f.label :delivery_map, class: "form-label" %>
<%= f.file_field :delivery_map,
class: "form-control",
accept: delivery_map_accepted_mime_types %>
accept: accepted_format_for_attachment(@site.class, "delivery_map") %>
<% if @site.delivery_map.attached? && @site.persisted? %>
<%= image_tag @site.delivery_map.representation(resize_to_limit: [200, 200]), class: "ms-0 mt-2" %>
<% end %>
Expand Down
23 changes: 23 additions & 0 deletions spec/helpers/application_helper_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

require "rails_helper"

RSpec.describe ApplicationHelper do
describe "accepted_format_for_attachment" do
context "with a model and attribute using ContentTypeValidator" do
it do
expect(helper.accepted_format_for_attachment(Site, "delivery_map")).to eq(
"image/png, image/jpeg, image/gif, application/pdf"
)
end
end

context "with a model using ContentTypeValidator (but not the attribute)" do
it { expect(helper.accepted_format_for_attachment(Site, "name")).to be_nil }
end

context "with a model not using ContentTypeValidator" do
it { expect(helper.accepted_format_for_attachment(Room, "name")).to be_nil }
end
end
end
9 changes: 0 additions & 9 deletions spec/helpers/sites_helper_spec.rb

This file was deleted.

0 comments on commit 9453d21

Please sign in to comment.