# `ToonEx.Fragment`
[🔗](https://github.com/ohhi-vn/toon_ex/blob/v1.1.0/lib/toon_ex/fragment.ex#L1)

Provides a way to inject an already-encoded TOON structure into a
to-be-encoded structure in optimized fashion.

This avoids a decoding/encoding round-trip for the subpart.

This feature can be used for caching parts of the TOON output, or delegating
the generation of the TOON to a third-party system (e.g. Postgres).

## Examples

    # From pre-encoded iodata
    fragment = ToonEx.Fragment.new("name: Alice")
    ToonEx.encode!(%{"user" => fragment})
    #=> "user:\n  name: Alice"

    # From an encoding function (lazy evaluation)
    fragment = ToonEx.Fragment.new(fn _opts -> "name: Alice" end)
    ToonEx.encode!(%{"user" => fragment})
    #=> "user:\n  name: Alice"

# `t`

```elixir
@type t() :: %ToonEx.Fragment{
  encode: (keyword() -&gt; iodata()),
  encode_key: (keyword() -&gt; iodata())
}
```

# `new`

```elixir
@spec new(iodata() | (keyword() -&gt; iodata())) :: t()
```

Creates a new fragment from pre-encoded iodata or an encoding function.

When given iodata (a binary or list), it will be returned as-is when the
fragment is encoded. When given a function, it receives the encoding options
and must return iodata — this allows lazy evaluation of the fragment content.

## Examples

    # From pre-encoded iodata
    fragment = ToonEx.Fragment.new("name: Alice")
    ToonEx.encode!(%{"user" => fragment})
    #=> "user:\n  name: Alice"

    # From an encoding function (lazy evaluation)
    fragment = ToonEx.Fragment.new(fn _opts -> "name: Alice" end)
    ToonEx.encode!(%{"user" => fragment})
    #=> "user:\n  name: Alice"

---

*Consult [api-reference.md](api-reference.md) for complete listing*
