Inspecting Ecto Schemas with Elixir
Stars aligned last week — while I was busy digging into how to document Ecto database schemas in some Elixir applications, I saw a relevant Stackoverflow post, basically asking how to do this very thing. So here’s my official un-official release of the package I had been working on: Inspecto. It inspects your Ecto schemas and can help enhance your application’s documentation.
Including a visual summary of your database can be a nice lift for your application documentation. I was hoping to achieve a standard Entity Relationship Diagram (ERD) using Mermaid-JS like I did for documenting component interconnectivity, but alas, that goal remains out of practical reach.
Why doesn’t this work with Mermaid (yet)? At the time of writing, Mermaid’s ERD syntax relies on newlines, but Elixir’s documentation generation will (by default) remove extraneous whitespaces (such as newlines), so this ends up invalidating the syntax and breaking the chart. Boo. However, even if you implemented your own documentation parser that preserved newlines, the Mermaid ERD charts are too limited: they only include the field name and its type, and any attempts to include additional information (such as the default value) messes up the formatting. So, I opted for generating simple HTML tables, and I hold out hope that in the future there will be a way to draw the foreign-key relationships between the tables. Stay tuned!
Yada yada yada, how do I include some database documentation in my app? You can simply call the Inspecto.summarize/2
function from inside a @moduledoc
tag, something like this:
defmodule MyApp.MyModel do
@moduledoc """
Here is a summary of my Ecto schemas: #{ MyApp.MyModel
|> Inspecto.modules()
|> Inspecto.summarize(format: :html) }
""" # ... any module code follows ...
end
Just be careful: anything inside a @moduledoc
block is evaluated at compile-time, so it’s possible that encountering a trivial problem with your non-essential nice-to-have documentation sweetener prevents your entire app from compiling.
That’s it. Have fun Inspecto-ing your database schemas!