Skip to content

Commit

Permalink
Merge pull request #338 from igorkasyanchuk/315-matcher-content_type-…
Browse files Browse the repository at this point in the history
…matcher-does-not-work-with-symbols

[Matcher] Add support for symbol content_types for content_type matcher options (#315)
  • Loading branch information
Mth0158 authored Dec 30, 2024
2 parents 5abb8a0 + 9b7b29a commit 5ed0ae7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ def failure_message
end

def allowing(*content_types)
@allowed_content_types = content_types.flatten
@allowed_content_types = content_types.map { |content_type| normalize_content_type(content_type) }.flatten
self
end

def rejecting(*content_types)
@rejected_content_types = content_types.flatten
@rejected_content_types = content_types.map { |content_type| normalize_content_type(content_type) }.flatten
self
end

Expand Down Expand Up @@ -88,6 +88,10 @@ def pluralize(types)
end
end

def normalize_content_type(content_type)
Marcel::MimeType.for(declared_type: content_type.to_s, extension: content_type.to_s)
end

def all_allowed_content_types_allowed?
@allowed_content_types_not_allowed ||= @allowed_content_types.reject { |type| type_allowed?(type) }
@allowed_content_types_not_allowed.empty?
Expand Down
2 changes: 2 additions & 0 deletions test/dummy/app/models/content_type/matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class ContentType::Matcher < ApplicationRecord
has_one_attached :allowing_several_through_regex
validates :allowing_several_through_regex, content_type: [/\Aimage\/.*\z/]

has_one_attached :allowing_symbol
validates :allowing_symbol, content_type: :png
has_one_attached :allowing_sneaky_edge_cases
validates :allowing_sneaky_edge_cases, content_type: ["image/svg+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]

Expand Down
11 changes: 11 additions & 0 deletions test/matchers/content_type_validator_matcher_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@
end

describe 'Edge cases' do
describe "when the passed content_type is a symbol (e.g. :png)" do
let(:model_attribute) { :allowing_symbol }
let(:allowed_type) { :png }

describe 'when provided with the exact allowed type' do
subject { matcher.allowing(allowed_type) }

it { is_expected_to_match_for(klass) }
end
end

describe "when the content_type specifier (e.g. 'svg+xml') is not strictly equal to the file extension (e.g. '.svg')" do
let(:model_attribute) { :allowing_sneaky_edge_cases }
let(:allowed_types) { ["image/svg+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] }
Expand Down

0 comments on commit 5ed0ae7

Please sign in to comment.