One of the things I’ve missed since coming to Elixir is a simple way to parse data from an external service (like JSON or MessagePack) into a structure that’s more suitable for my application.
I finally got tired of writing transformations from maps with string keys to structs and stole one of Go’s best ideas.
Forma parses a typespec that you provide and tries to shape your input data to fit into that typespec.
For example:
defmodule User do
defstruct [:id, :name, :age, :gender]
@type t :: %__MODULE__{
id: String.t,
name: String.t,
age: non_neg_integer(),
gender: :male | :female | :other | :prefer_not_to_say
}
end
Forma.parse(%{"id" => "1", "name" => "Fredrik", "age" => 30, "gender" => "male"}, User)
# => {:ok, %User{id: "1", name: "Fredrik", age: 30, gender: :male}}
It doesn’t do any parsing of its own, but works great together with e.g Poison or jiffy. It supports most cases I’ve stumbled across thus far, but it’s still pretty early in development.
Feedback, ideas for improvements as well as bug reports are welcome!