View Source Ecspanse.Template.Component behaviour (ECSpanse v0.10.0)

A template component is a generic way of defining the structure for related components. They share the same state fields and tags.

The template component, coupled with tags allow a flexible way to manage collections of related components. See Ecspanse.Component for more details.

The template component guarantees that the component that uses it will have certain fields in its state and certain tags. The component itself can define additional fields or tags, specific to its implementation. It can also override the initial values of the template fields.

The framework embeds some predefined component templates:

Options

See Ecspanse.Component for the list of options.

Examples

    defmodule Demo.Componenets.Resource do
      use Ecspanse.Template.Component, state: [amount: 0], tags: [:resource]
    end

    defmodule Demo.Componenets.Gold do
      use Demo.Components.Resource, state: [amount: 5, exchange_rate: 2], tags: [:available]
    end

Summary

Callbacks

Optional callback to validate the template and component state fields.

Callbacks

Link to this callback

validate(state)

View Source (optional)
@callback validate(state :: keyword()) :: :ok | {:error, any()}

Optional callback to validate the template and component state fields.

It runs only at compile time, and it takes the list of fields as the only argument and returns :ok or an error tuple.

Info

When an error tuple is returned, it raises an exception with the provided error message.

For runtime component state validation see Ecspanse.Component.validate/1.

Examples

  defmodule Demo.Components.Resources do
    use Ecspanse.Template.Component, state: [amount: 0]

    def validate(state_fields) do
      amount = Keyword.get(state_fields, :amount, 0)
      if is_integer(amount) and amount >= 0 do
        :ok
      else
        {:error, "Invalid amount value"}
      end
    end
  end