Skip to content

Commit

Permalink
ALlow suffixes to be customizable
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed May 31, 2023
1 parent 37da333 commit d8a2943
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
30 changes: 21 additions & 9 deletions lib/mime.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ defmodule MIME do
Note that defining a new type will completely override all
previous extensions. You can use `MIME.extensions/1` to get
the existing extension to add whenever defining.
the existing extension to keep when redefining.
You can also customize the extensions for suffixes. For example,
the mime type "application/custom+gzip" returns the extension
`".gz"` because the suffix "gzip" maps to `["gz"]`:
config :mime, :suffixes, %{
"gzip" => ["gz"]
}
After adding the configuration, MIME needs to be recompiled
if you are using an Elixir version earlier than v1.15. In such
Expand Down Expand Up @@ -117,14 +125,6 @@ defmodule MIME do
"video/x-msvideo" => ["avi"]
}

#selected from https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
suffixes = %{
"gzip" => ["gz"],
"json" => ["json"],
"xml" => ["xml"],
"zip" => ["zip"]
}

require Application
custom_types = Application.compile_env(:mime, :types, %{})

Expand All @@ -148,6 +148,18 @@ defmodule MIME do
raise "conflicting MIMEs for extension .#{ext}, please override: #{inspect(mimes)}"
end


# https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
default_suffixes = %{
"gzip" => ["gz"],
"json" => ["json"],
"xml" => ["xml"],
"zip" => ["zip"]
}

custom_suffixes = Application.compile_env(:mime, :suffixes, %{})
suffixes = Map.merge(default_suffixes, custom_suffixes)

@doc """
Returns the custom types compiled into the MIME module.
"""
Expand Down
10 changes: 10 additions & 0 deletions test/mime_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,14 @@ defmodule MIMETest do
assert MIME.type("txt") == "application/octet-stream"
assert MIME.type("text") == "application/octet-stream"
end

test "overrides suffixes" do
Application.put_env(:mime, :suffixes, %{"custom-format" => ["cf"]})

[File.cwd!(), "lib", "mime.ex"]
|> Path.join()
|> Code.compile_file()

assert MIME.extensions("text/plain+custom-format") == ["cf"]
end
end

0 comments on commit d8a2943

Please sign in to comment.