Readable v0.3.0 Read View Source

Provides utilities to implement and work with Readable types

Link to this section Summary

Functions

Helper to define readable relation for pair of types. Accepts

Strict macro helper to read expression into given type. Returns compile-time error if target type does not exist.

Helper to read expression into given type

Link to this section Functions

Link to this macro

defreadable(quoted_to_type, list1, list2) View Source (macro)

Helper to define readable relation for pair of types. Accepts:

  • target type which we want to read
  • source arg expression :: type pair
  • block of code where relation is described

Examples

iex> quote do
...>   import Read
...>   defreadable URI, from: x :: BitString do
...>     URI.parse(x)
...>   end
...> end
...> |> Code.compile_quoted
iex> import Read
iex> read("https://hello.world", URI)
%URI{
  authority: "hello.world",
  fragment: nil,
  host: "hello.world",
  path: nil,
  port: 443,
  query: nil,
  scheme: "https",
  userinfo: nil
}

iex> quote do
...>   import Read
...>   defreadable NaiveDateTime, from: x :: Tuple do
...>     case NaiveDateTime.from_erl(x) do
...>       {:ok, y} -> y
...>       {:error, _} -> fail!(x)
...>     end
...>   end
...> end
...> |> Code.compile_quoted
iex> import Read
iex> read({{2000, 1, 1}, {13, 30, 15}}, NaiveDateTime)
~N[2000-01-01 13:30:15]
iex> read({{2000, 13, 1}, {13, 30, 15}}, NaiveDateTime)
** (Readable.Exception) NaiveDateTime can not be read from {{2000, 13, 1}, {13, 30, 15}}
Link to this macro

mk_read(from_expression, quoted_to_type) View Source (macro)

Strict macro helper to read expression into given type. Returns compile-time error if target type does not exist.

Examples

iex> import Read
iex> mk_read("123", Integer)
123
iex> quote do
...>   import Read
...>   mk_read("123", TypeNotExist)
...> end
...> |> Code.eval_quoted()
** (UndefinedFunctionError) function TypeNotExist.__struct__/0 is undefined (module TypeNotExist is not available)
Link to this function

read(from_expression, to_type) View Source

Helper to read expression into given type

Examples

iex> Read.read("1", Integer)
1