Skip to content

Commit

Permalink
Add types for marcel (#545)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
tk0miya authored May 6, 2024
1 parent a04c0e9 commit 7a105f5
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
28 changes: 28 additions & 0 deletions gems/marcel/1.0/_test/test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require "marcel"
require "pathname"
require "stringio"

# Magic bytes sniffing alone
Marcel::MimeType.for Pathname.new("example.gif")
# => "image/gif"

File.open "example.gif" do |file|
Marcel::MimeType.for file
end
# => "image/gif"

# Magic bytes with filename fallback
Marcel::MimeType.for Pathname.new("unrecognisable-data"), name: "example.pdf"
# => "application/pdf"

# File extension alone
Marcel::MimeType.for extension: ".pdf"
# => "application/pdf"

# Magic bytes, declared type, and filename together
Marcel::MimeType.for Pathname.new("unrecognisable-data"), name: "example", declared_type: "image/png"
# => "image/png"

# Safe fallback to application/octet-stream
Marcel::MimeType.for StringIO.new(File.read "unrecognisable-data")
# => "application/octet-stream"
2 changes: 2 additions & 0 deletions gems/marcel/1.0/manifest.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dependencies:
- name: pathname
13 changes: 13 additions & 0 deletions gems/marcel/1.0/marcel.rbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Marcel
class Magic
attr_reader type: String
attr_reader mediatype: String
attr_reader subtype: String

def self.by_magic: (IO | StringIO) -> instance
end

class MimeType
def self.for: (?Pathname | IO | StringIO pathname_or_io, ?name: String, ?extension: String, ?declared_type: String) -> String
end
end

0 comments on commit 7a105f5

Please sign in to comment.