yggdrasil v4.0.0 Yggdrasil.Transformer behaviour View Source

Transformer behaviour that defines how to decode and encode messages from a Yggdrasil.Channel.

Small example

Let’s say we want to implement a transformer to send any Elixir term as a string to our subscribers. The transformer module would be implemented as follows:

defmodule Yggdrasil.Transformer.Code do
  use Yggdrasil.Transformer

  def decode(_channel, message) do
    with {decoded, []} <- Code.eval_string(message) do
      {:ok, decoded}
    else
      _ ->
        {:error, "Bad message"}
    end
  end

  def encode(_channel, message) do
    encoded = inspect(message)
    {:ok, encoded}
  end
end

And we could use the following Channel to publish or subscribe to this messages:

%Channel{
  name: "my_channel",
  adapter: :redis,
  transformer: Yggdrasil.Transformer.Code
}

Transformer alias

When defining transformers it is possible to define aliases for the module as follows:

defmodule Yggdrasil.Transformer.Code do
  use Yggdrasil.Transformer, name: :code

  (... same implementation as above ...)
end

And adding the following to our application supervision tree:

Supervisor.start_link([
  {Yggdrasil.Transformer.Code, []}
  ...
])

This will allow you to use the following as a Channel to subscribe and publish:

%Channel{name: "my_channel", adapter: :redis, transformer: :code}

Link to this section Summary

Functions

Generic message decoder for a channel

Generic message encoder for a channel

Callbacks

Callback to define how to decode the messages coming from a channel

Callback to define how to encode the messages going to a channel

Link to this section Functions

Link to this macro __using__(options) View Source (macro)

Macro for using Yggdrasil.Transformer.

The following are the available options:

  • :name - Name of the transformer. Must be an atom.
Link to this function decode(channel, message) View Source
decode(Yggdrasil.Channel.t(), term()) :: {:ok, term()} | {:error, term()}

Generic message decoder for a channel.

Link to this function encode(channel, message) View Source
encode(Yggdrasil.Channel.t(), term()) :: {:ok, term()} | {:error, term()}

Generic message encoder for a channel.

Link to this section Callbacks

Link to this callback decode(channel, message) View Source
decode(channel :: Yggdrasil.Channel.t(), message :: term()) ::
  {:ok, term()} | {:error, term()}

Callback to define how to decode the messages coming from a channel.

Link to this callback encode(channel, message) View Source
encode(channel :: Yggdrasil.Channel.t(), message :: term()) ::
  {:ok, term()} | {:error, term()}

Callback to define how to encode the messages going to a channel.