Plushie.Event.EventType behaviour (Plushie v0.6.0)

Copy Markdown View Source

Behaviour for custom event field types.

Event declarations use type identifiers to describe the shape of event data. Built-in atomic types (:number, :string, :boolean, :any) are handled implicitly. Module types implement this behaviour to provide custom parsing from wire-format values to Elixir types.

Built-in atomic types

These types pass through with validation only (no transformation):

  • :number -- integer or float
  • :string -- binary
  • :boolean -- true or false
  • :any -- any term, no validation

Module types

Any module that implements this behaviour can be used as a type in event declarations. The module must define parse/1, which transforms a wire-format value into an Elixir value.

Example

defmodule MyApp.Direction do
  @behaviour Plushie.EventType

  @impl true
  def parse("up"), do: {:ok, :up}
  def parse("down"), do: {:ok, :down}
  def parse("left"), do: {:ok, :left}
  def parse("right"), do: {:ok, :right}
  def parse(_), do: :error
end

Then in an event declaration:

event :swipe, data: [direction: MyApp.Direction]

Summary

Callbacks

Parses a wire-format value into an Elixir value.

Functions

Returns the list of built-in atomic type identifiers.

Parses a value according to a type identifier.

Returns true if the given type identifier is valid for event fields.

Callbacks

parse(term)

@callback parse(term()) :: {:ok, term()} | :error

Parses a wire-format value into an Elixir value.

Returns {:ok, parsed_value} on success, or :error if the value cannot be parsed.

Functions

builtin_atomic_types()

@spec builtin_atomic_types() :: [atom()]

Returns the list of built-in atomic type identifiers.

parse_field(module, value)

@spec parse_field(type :: atom(), value :: term()) :: {:ok, term()} | :error

Parses a value according to a type identifier.

For built-in atomic types, validates the value matches the expected type. For module types, delegates to module.parse/1.

The :string type accepts nil in addition to binaries, since wire-format event fields may be absent (decoded as nil).

Returns {:ok, value} on success, :error on failure.

valid_type?(type)

@spec valid_type?(type :: term()) :: boolean()

Returns true if the given type identifier is valid for event fields.

Valid types are built-in atoms or modules implementing this behaviour.