NLdoc.SpecDef.Schema (NLdoc.SpecDef v1.0.5)

View Source

This module sets some defaults over the Ecto schema for the NLdoc spec.

  1. Use this in all schemas for the NLdoc spec, instead of use Ecto.Schema or use TypedEctoSchema: use NLdoc.SpecDef.Schema, type: "https://spec.nldoc.nl/Resource/Foo"
  2. Implement the changeset/2 function in the schema module.
  3. Make sure to add @cast_opts to all calls to cast/4 or cast_embed/3 or cast_polymorphic_embed/3, as it ensures strings that only contain whitespace are accepted as valid.

Note: the type option is required and must be a string. It is the resource type of the schema. It will be available as @resource_type in the schema module and through the resource_type/0 function on the schema module.

Example

defmodule Example do
  @moduledoc false

  use NLdoc.SpecDef.Schema, type: "https://spec.foo.com/example"

  typed_embedded_schema null: false do
    field :type, :string, default: @resource_type
    field :message, :string
  end

  def changeset(object, attrs) do
    fields = [:type, :message]

    object
    |> cast(attrs, fields, @cast_opts)
    |> validate_required(fields)
    |> validate_inclusion(:type, [@resource_type])
  end
end

Summary

Functions

This macro defines the new/1 and new!/1 functions for the schema module that create a new document from a template, which essentially functions like an input-validating constructor for the struct defined by the schema module.

Functions

def_constructor(_)

(macro)

This macro defines the new/1 and new!/1 functions for the schema module that create a new document from a template, which essentially functions like an input-validating constructor for the struct defined by the schema module.