View Source Ymlr.Encoder protocol (ymlr v4.0.0)

Protocol controlling how a value is encoded to YAML.

deriving

Deriving

The protocol allows leveraging the Elixir's @derive feature to simplify protocol implementation in trivial cases. 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.

example

Example

Let's assume a presence of the following struct:

defmodule Test do
  defstruct [:foo, :bar, :baz]
end

If we were to call @derive Ymlr.Encoder just before defstruct, an implementation similar to the following implementation would be generated:

defimpl Ymlr.Encoder, for: Test do
  def encode(data, idnent_level) do
    data
    |> Map.take(unquote([:foo, :bar, :baz]))
    |> Ymlr.Encode.map(idnent_level)
  end
end

limit-fields-using-the-only-option

Limit fields using the only Option

We can limit the fields being encoded using the :only option:

defmodule Test do
  @derive {Ymlr.Encoder, only: [:foo]}
  defstruct [:foo, :bar, :baz]
end

This would generate an implementation similar to the following:

defimpl Ymlr.Encoder, for: Test do
  def encode(data, idnent_level) do
    data
    |> Map.take(unquote([:foo]))
    |> Ymlr.Encode.map(idnent_level)
  end
end

exclude-fields-using-the-except-option

Exclude fields using the except Option

We can exclude the fields being encoded using the :except option:

defmodule Test do
  @derive {Ymlr.Encoder, except: [:foo]}
  defstruct [:foo, :bar, :baz]
end

This would generate an implementation similar to the following:

defimpl Ymlr.Encoder, for: Test do
  def encode(data, idnent_level) do
    data
    |> Map.take(unquote([:bar, :baz]))
    |> Ymlr.Encode.map(idnent_level)
  end
end

Link to this section Summary

Functions

Encodes the given data to YAML.

Link to this section Types

Link to this section Functions

Link to this function

encode(data, idnent_level, opts)

View Source
@spec encode(data :: term(), idnent_level :: integer(), opts :: opts()) :: iodata()

Encodes the given data to YAML.