Skip to content

Commit d8a2943

Browse files
committed
ALlow suffixes to be customizable
1 parent 37da333 commit d8a2943

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

lib/mime.ex

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,15 @@ defmodule MIME do
1111
1212
Note that defining a new type will completely override all
1313
previous extensions. You can use `MIME.extensions/1` to get
14-
the existing extension to add whenever defining.
14+
the existing extension to keep when redefining.
15+
16+
You can also customize the extensions for suffixes. For example,
17+
the mime type "application/custom+gzip" returns the extension
18+
`".gz"` because the suffix "gzip" maps to `["gz"]`:
19+
20+
config :mime, :suffixes, %{
21+
"gzip" => ["gz"]
22+
}
1523
1624
After adding the configuration, MIME needs to be recompiled
1725
if you are using an Elixir version earlier than v1.15. In such
@@ -117,14 +125,6 @@ defmodule MIME do
117125
"video/x-msvideo" => ["avi"]
118126
}
119127

120-
#selected from https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
121-
suffixes = %{
122-
"gzip" => ["gz"],
123-
"json" => ["json"],
124-
"xml" => ["xml"],
125-
"zip" => ["zip"]
126-
}
127-
128128
require Application
129129
custom_types = Application.compile_env(:mime, :types, %{})
130130

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

151+
152+
# https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
153+
default_suffixes = %{
154+
"gzip" => ["gz"],
155+
"json" => ["json"],
156+
"xml" => ["xml"],
157+
"zip" => ["zip"]
158+
}
159+
160+
custom_suffixes = Application.compile_env(:mime, :suffixes, %{})
161+
suffixes = Map.merge(default_suffixes, custom_suffixes)
162+
151163
@doc """
152164
Returns the custom types compiled into the MIME module.
153165
"""

test/mime_test.exs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,14 @@ defmodule MIMETest do
6969
assert MIME.type("txt") == "application/octet-stream"
7070
assert MIME.type("text") == "application/octet-stream"
7171
end
72+
73+
test "overrides suffixes" do
74+
Application.put_env(:mime, :suffixes, %{"custom-format" => ["cf"]})
75+
76+
[File.cwd!(), "lib", "mime.ex"]
77+
|> Path.join()
78+
|> Code.compile_file()
79+
80+
assert MIME.extensions("text/plain+custom-format") == ["cf"]
81+
end
7282
end

0 commit comments

Comments
 (0)