ToonEx.Encoder protocol (toon_ex v1.1.0)

Copy Markdown View Source

Protocol for encoding custom data structures to TOON format.

This protocol allows you to define how your custom structs should be encoded to TOON format, similar to Jason.Encoder.

Deriving

The protocol leverages Elixir's @derive feature. Accepted options are:

  • :only - encodes only values of specified keys.
  • :except - encodes all struct fields except specified keys.

By default all keys except the :__struct__ key are encoded.

The generated implementation pre-computes key encoding at compile time for maximum runtime efficiency (inspired by Jason.Encoder).

Example

defmodule User do
  @derive {ToonEx.Encoder, only: [:name, :email]}
  defstruct [:id, :name, :email, :password_hash]
end

Or implement the protocol manually:

defimpl ToonEx.Encoder, for: User do
  def encode(user, opts) do
    %{
      "name" => user.name,
      "email" => user.email
    }
    |> ToonEx.Encode.encode!(opts)
  end
end

Summary

Types

t()

All the types that implement this protocol.

Functions

Encodes the given value to TOON format.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(value, opts)

@spec encode(
  t(),
  keyword()
) :: iodata() | map()

Encodes the given value to TOON format.

Returns IO data that can be converted to a string.