From 7a105f52053ce1c708b605dfa9c1ab8473424036 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Tue, 7 May 2024 01:01:34 +0900 Subject: [PATCH] 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 --- gems/marcel/1.0/_test/test.rb | 28 ++++++++++++++++++++++++++++ gems/marcel/1.0/manifest.yaml | 2 ++ gems/marcel/1.0/marcel.rbs | 13 +++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 gems/marcel/1.0/_test/test.rb create mode 100644 gems/marcel/1.0/manifest.yaml create mode 100644 gems/marcel/1.0/marcel.rbs diff --git a/gems/marcel/1.0/_test/test.rb b/gems/marcel/1.0/_test/test.rb new file mode 100644 index 00000000..6f87358e --- /dev/null +++ b/gems/marcel/1.0/_test/test.rb @@ -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" diff --git a/gems/marcel/1.0/manifest.yaml b/gems/marcel/1.0/manifest.yaml new file mode 100644 index 00000000..7a30e313 --- /dev/null +++ b/gems/marcel/1.0/manifest.yaml @@ -0,0 +1,2 @@ +dependencies: + - name: pathname diff --git a/gems/marcel/1.0/marcel.rbs b/gems/marcel/1.0/marcel.rbs new file mode 100644 index 00000000..ead57d08 --- /dev/null +++ b/gems/marcel/1.0/marcel.rbs @@ -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