AshTypst.Code protocol (ash_typst v0.3.0)

Copy Markdown View Source

Protocol to support Typst code syntax.

Summary

Types

t()

All the types that implement this protocol.

Functions

Encode Elixir data structures into Typst code syntax.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(value, context)

Encode Elixir data structures into Typst code syntax.

Examples

iex> AshTypst.Code.encode(~U[2015-01-13 13:00:07Z], %{timezone: "America/New_York"})
"datetime(year: 2015, month: 1, day: 13, hour: 8, minute: 0, second: 7)"

iex> AshTypst.Code.encode(nil, %{})
"none"

iex> AshTypst.Code.encode(%{true: true, false: false, other: :other}, %{})
"(\"false\": false, \"true\": true, \"other\": \"other\")"

iex> AshTypst.Code.encode(["one", 2, 3.0], %{})
"(\"one\", int(2), float(3.0))"

The following types are supported by default:

Structs (including Ash resources) are not encoded unless they opt in. Add @derive AshTypst.Code to the module to use the built-in implementation (which serializes an Ash resource's public fields), or implement the protocol directly with defimpl AshTypst.Code, for: MyStruct for full control:

defmodule MyApp.Invoice do
  use Ash.Resource, domain: MyApp.Domain

  @derive AshTypst.Code

  # ...
end

Context must be passed through. This allows for things like dates to be formatted according to a given timezone, etc.

If timezone is specified in the context, supported types will be automatically shifted to that zone. Ensure you install and configure your choice of timezone database in config.exs:

config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
config :elixir, :time_zone_database, TimeZoneInfo.TimeZoneDatabase
config :elixir, :time_zone_database, Zoneinfo.TimeZoneDatabase
config :elixir, :time_zone_database, Tz.TimeZoneDatabase