Skip to content

Commit

Permalink
Regression fix: binary declared type should fall back to filename ext…
Browse files Browse the repository at this point in the history
…ension type

The application/octet-stream content type is treated as a default rather
than a specific declaration. We should check the filename extension for
the more specific type in this case. If there's no extension, the type
falls back to binary anyway.

Fixes regression in 1.0.2 -> 1.0.3 introduced by #94.
  • Loading branch information
jeremy committed Mar 1, 2024
1 parent 59d23fd commit 1307646
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
7 changes: 6 additions & 1 deletion lib/marcel/mime_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ def for_extension(extension)
end

def for_declared_type(declared_type)
parse_media_type(declared_type)
type = parse_media_type(declared_type)

# application/octet-stream is treated as an undeclared/missing type,
# allowing the type to be inferred from the filename. If there's no
# filename extension, then the type falls back to binary anyway.
type unless type == BINARY
end

def with_io(pathname_or_io, &block)
Expand Down
11 changes: 8 additions & 3 deletions test/declared_type_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@
require 'rack'

class Marcel::MimeType::DeclaredTypeTest < Marcel::TestCase
test "returns declared type as last resort" do
assert_equal "text/html", Marcel::MimeType.for(name: "unrecognisable", declared_type: "text/html")
test "prefers declared type over filename extension" do
assert_equal "text/html", Marcel::MimeType.for(name: "file.txt", declared_type: "text/html")
end

test "returns application/octet-stream if declared type empty or unrecognised" do
test "prefers filename extension over binary type" do
assert_equal "text/plain", Marcel::MimeType.for(name: "file.txt", declared_type: "application/octet-stream")
end

test "defaults to binary if declared type is unrecognized" do
assert_equal "application/octet-stream", Marcel::MimeType.for(declared_type: nil)
assert_equal "application/octet-stream", Marcel::MimeType.for(declared_type: "")
assert_equal "application/octet-stream", Marcel::MimeType.for(declared_type: "unrecognised")
end
Expand Down

0 comments on commit 1307646

Please sign in to comment.