ToonEx.Helpers (toon_ex v1.1.0)

Copy Markdown View Source

Provides macro facilities for partial compile-time encoding of TOON.

These macros encode keys at compile time and strive to create as flat an iodata structure as possible to achieve maximum efficiency. The encoding happens right at the call site, but returns a %ToonEx.Fragment{} struct that needs to be passed to one of the "main" encoding functions — for example ToonEx.encode!/2 for final encoding into TOON — this makes it completely transparent for most uses.

Only allows keys that are safe unquoted TOON keys (matching ^[A-Za-z_][A-Za-z0-9_.]*$).

Example

# Compile-time encoded map fragment
fragment = ToonEx.Helpers.toon_map(foo: 1, bar: "hello")
ToonEx.encode!(%{"data" => fragment})
#=> "data:\n  bar: hello\n  foo: 1"

# Compile-time encoded map with variable values
x = 42
fragment = ToonEx.Helpers.toon_map(count: x, name: "test")
ToonEx.encode!(fragment)
#=> "count: 42\nname: test"

Summary

Functions

Encodes a TOON map from a compile-time keyword list.

Encodes a TOON map from a variable containing a map and a compile-time list of keys.

Functions

toon_map(kv)

(macro)

Encodes a TOON map from a compile-time keyword list.

Keys are validated and encoded at compile time. Values are encoded at runtime. The result is a %ToonEx.Fragment{} that can be embedded in any TOON encoding.

Only allows keys that are safe unquoted TOON keys (matching ^[A-Za-z_][A-Za-z0-9_.]*$).

Examples

fragment = toon_map(name: "Alice", age: 30)
ToonEx.encode!(fragment)
"age: 30\nname: Alice"

toon_map_take(map, take)

(macro)

Encodes a TOON map from a variable containing a map and a compile-time list of keys.

It is equivalent to calling Map.take/2 before encoding. Keys are encoded at compile time.

Examples

map = %{a: 1, b: 2, c: 3}
fragment = toon_map_take(map, [:c, :b])
ToonEx.encode!(fragment)
"b: 2\nc: 3"