Defmap is a utility which allows you to embed a map into a module for faster/easier lookups. A lot of times you may want to have lookup tables in your app. e.g. when you need to map error codes to messages. Using Defmap, you directly embed the lookup map/table into your module, this improves the performance and decreases the memory used.
defmodule HttpStatusMessages do
use Defmap, map: %{
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
}
end
IO.inspect HttpStatusMessages.get(401) # => {:ok, "Unauthorized"}
IO.inspect HttpStatusMessages.get(3) # => :error
defmodule HttpStatusMessages do
use Defmap, func_name: :get_message, map: %{
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
}
end
IO.inspect HttpStatusMessages.get_message(401) # => {:ok, "Unauthorized"}
IO.inspect HttpStatusMessages.get_message(3) # => :error
defmodule HttpStatusMessages do
use Defmap, func_name: :get_message, map: %{
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
}
use Defmap, func_name: :get_detailed_info, map: %{
400 => "Bad Request, happens when your input is invalid",
401 => "Unauthorized, happens when you don't have enough privileges",
}
end
IO.inspect HttpStatusMessages.get_message(401) # => {:ok, "Unauthorized"}
IO.inspect HttpStatusMessages.get_message(3) # => :error
IO.inspect HttpStatusMessages.get_detailed_info(401) # => {:ok, "Bad Request, happens when your input is invalid"}
IO.inspect HttpStatusMessages.get_detailed_info(3) # => :error
Contents of ./http_statuses.csv
417, Expectation Failed
500, Internal Server Error
205, Reset Content
...
defmodule HttpStatuses do
use Defmap, map: (File.stream!(Path.expand(Path.join(__DIR__, "./http_statuses.csv")))
|> CSV.decode
|> Enum.reject(& length(&1) != 2)
|> Enum.map(fn [k, v] -> {String.to_integer(k), String.strip(v)} end)
|> Enum.into(%{})),
func_name: :get_status
end
IO.inspect HttpStatusMessages.get_status(401) # => {:ok, "Unauthorized"}
IO.inspect HttpStatusMessages.get_status(3) # => :error
The package can be installed as:
- Add
defmap
to your list of dependencies inmix.exs
:
def deps do
[{:defmap, "~> 0.1.0"}]
end
- Ensure
defmap
is started before your application:
def application do
[applications: [:defmap]]
end