Nestru.Encoder protocol (Nestru v1.0.1) View Source

Link to this section Summary

Functions

Returns the fields gathered from the given struct, which can be encoded further.

Link to this section Types

Link to this section Functions

Link to this function

gather_fields_from_struct(struct, context)

View Source

Returns the fields gathered from the given struct, which can be encoded further.

It can be used to rename the keys of the map, or to turn the whole struct to binary.

The first argument is the encodable struct value adopting the protocol.

The second argument is the context given to encode/2 or encode_to_list/2 functions.

Nestru calls this function as the first step of the encoding procedure.

If the function returns {:ok, item}, then the encoding continues depending on the value of the item as follows:

  • for a binary, the encoding finishes, and the binary is returned
  • for a map, the encoding continues for each key-value pair. If the value is a struct then it is encoded into a map with encode/1, the same is done recursively for lists, all other values are left as they are.

If the function returns {:error, message} tuple, then encoding stops, and the error is bypassed to the caller.

Any other return value raises an error.

To generate the default implementation of the function, add the @derive Nestru.Encoder attribute to the struct. The :only and :except options are supported to filter the fields.

The default implementation gathers keys from the struct by calling Map.from_struct/1.

Examples

def Supplier do
  # Derive the default implementation
  @derive Nestru.Encoder

  defstruct [:id, :name]
end

def Purchaser do
  # Encode only one field
  @derive {Nestru.Encoder, only: [:id]}

  defstruct [:id, :name, :address]
end

defmodule BoxLabel do
  defstruct [:prefix, :number]

  # Encode label as a binary
  defimpl Nestru.Encoder do
    def gather_fields_from_struct(struct, _context) do
      {:ok, "FF{struct.prefix}-{struct.number}"}
    end
  end
end

defmodule FruitBox do
  defstruct [:items, :label]

  # Rename the :items key to :elements in the result map
  defimpl Nestru.Encoder do
    def gather_fields_from_struct(struct, _context) do
      map = Map.from_struct(struct)

      {:ok,
       map
       |> Map.put(:elements, Map.get(map, :items))
       |> Map.delete(:items)}
    end
  end
end