Skuld.Comp.DefOp (skuld v0.1.8)

View Source

Macro for defining serializable operation structs.

Defines a struct module with Jason.Encoder implementation for JSON serialization via Skuld.Comp.SerializableStruct.

Example

defmodule Skuld.Effects.State do
  import Skuld.Comp.DefOp

  def_op Get
  def_op Put, [:value]

  # Creates:
  # - Skuld.Effects.State.Get with defstruct []
  # - Skuld.Effects.State.Put with defstruct [:value]
  # - Jason.Encoder implementations for both
end

The structs can then be used as effect arguments:

def get, do: Skuld.Comp.effect(@sig, %Get{})
def put(value), do: Skuld.Comp.effect(@sig, %Put{value: value})

And serialized to JSON:

Jason.encode!(%State.Put{value: 42})
# => {"__struct__":"Elixir.Skuld.Effects.State.Put","value":42}

Atom Fields

Some fields may contain atoms (like tags) that need to be converted back from strings during JSON deserialization. Use the atom_fields option:

def_op Get, [:tag], atom_fields: [:tag]

This generates a from_json/1 callback that converts the specified fields from strings to existing atoms.

Summary

Functions

Define an operation struct with JSON serialization.

Functions

def_op(mod, fields \\ [], opts \\ [])

(macro)

Define an operation struct with JSON serialization.

Arguments

  • mod - the module name (will be nested under the calling module)
  • fields - list of struct fields (default: [])
  • opts - keyword options:
    • atom_fields - list of fields that should be converted from strings to atoms during deserialization