Spect v0.3.1 Spect
elixir typespec enhancements
Link to this section Summary
Link to this section Functions
decodes an object from a typespec, raising on error
typespec-driven object decoding
This function converts a data structure into a new one derived from a type specification. This provides for the effective decoding of (nested) data structures from serialization formats that do not support Elixir’s rich set of types (json, etc.). Atoms can be decoded from strings, tuples from lists, structs from maps, etc.
data is the data structure to decode, module is the name of the module
containing the type specification, and name is the name of the @type
definition within the module (defaults to :t).
As mentioned above, a common use case is to decode a JSON document into an Elixir struct, for example using the poison parser:
"test.json"
|> File.read!()
|> Poison.Parser.parse!()
|> Spect.to_spec!(My.Master)
where the My module might contain the following structs:
defmodule My do
defmodule Master do
@type t :: %__MODULE__{
rest: integer(),
details: %{String.t() => My.Detail.t()}
}
defstruct [rest: 2, details: %{}]
end
defmodule Detail do
@type t :: %__MODULE__{
nest: integer()
}
defstruct [nest: 1]
end
end