Skip to content

Commit 7a105f5

Browse files
authored
Add types for marcel (#545)
Marcel chooses the most appropriate content type for a file by inspecting its contents, the declared MIME type (perhaps passed as a Content-Type header), and the file extension. refs: https://github.com/rails/marcel
1 parent a04c0e9 commit 7a105f5

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

gems/marcel/1.0/_test/test.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
require "marcel"
2+
require "pathname"
3+
require "stringio"
4+
5+
# Magic bytes sniffing alone
6+
Marcel::MimeType.for Pathname.new("example.gif")
7+
# => "image/gif"
8+
9+
File.open "example.gif" do |file|
10+
Marcel::MimeType.for file
11+
end
12+
# => "image/gif"
13+
14+
# Magic bytes with filename fallback
15+
Marcel::MimeType.for Pathname.new("unrecognisable-data"), name: "example.pdf"
16+
# => "application/pdf"
17+
18+
# File extension alone
19+
Marcel::MimeType.for extension: ".pdf"
20+
# => "application/pdf"
21+
22+
# Magic bytes, declared type, and filename together
23+
Marcel::MimeType.for Pathname.new("unrecognisable-data"), name: "example", declared_type: "image/png"
24+
# => "image/png"
25+
26+
# Safe fallback to application/octet-stream
27+
Marcel::MimeType.for StringIO.new(File.read "unrecognisable-data")
28+
# => "application/octet-stream"

gems/marcel/1.0/manifest.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
dependencies:
2+
- name: pathname

gems/marcel/1.0/marcel.rbs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
module Marcel
2+
class Magic
3+
attr_reader type: String
4+
attr_reader mediatype: String
5+
attr_reader subtype: String
6+
7+
def self.by_magic: (IO | StringIO) -> instance
8+
end
9+
10+
class MimeType
11+
def self.for: (?Pathname | IO | StringIO pathname_or_io, ?name: String, ?extension: String, ?declared_type: String) -> String
12+
end
13+
end

0 commit comments

Comments
 (0)