Documenting Ecto fields with module attributes

is there a standard way to document Ecto fields? Like e.g.

schema "table" do
  @doc """
  The name
  """
  field :name, :string

  @doc """
  The place
  """
  field :place, :string
end

:point_up: when I try this I get a warning about @doc being defined twice.

Is there some standard field-specific module attribute I should be using? Or am I going to have to stick everything in a single @doc and not be able to make it granular by field?

The only thing that comes to mind is adding comments to SQL tables or columns. But that does not seem to be what you are after.

1 Like

Sadly, there is no official support for this. In a project that I used to work, we were building on top of Ecto.Schema to be able to define documentation for fields, then we could generate it alongside other module documentation with some metaprogramming magic.

Sadly, this is not entirely trivial to re-create, otherwise I would have showed you an example of how something like that can be done.

2 Likes

Lately I have been sticking comments above the fields. They don’t show up in the docs, but we aren’t rendering them often.

1 Like

David Bernheisel has a good tip in his blog: Ecto Tips: UUID Boilerplate, Docs, and Composing Changesets · Bernheisel

About 3/4 down in a section “Have Elixir Write Docs For You”, he demonstrates using module attributes to include field info in the docs and schema definitions. You could expand upon that idea to get close to what you want.

1 Like

You could use typedocs:

@typedoc "The name"
@type name :: String.t()

@typedoc "The place"
@type place :: String.t()

@typedoc "A table."
@type t :: %__MODULE__{name: name(), place: place()}
4 Likes