NLdoc.SpecDef.Schema (NLdoc.SpecDef v1.0.13)
View SourceThis module sets some defaults over the Ecto schema for the NLdoc spec.
- Use this in all schemas for the NLdoc spec, instead of
use Ecto.Schemaoruse TypedEctoSchema:use NLdoc.SpecDef.Schema, type: "https://spec.nldoc.nl/Resource/Foo" - Implement the
changeset/2function in the schema module. - Make sure to add
@cast_optsto all calls tocast/4orcast_embed/3orcast_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.