Ecto | How to get all schema modules in the application
Asked Answered
K

1

6

I'm trying to create a mix task for automation some scaffolding and I want to get a list of all module names in the application which have schema and embed schema implementations. Eventually I'd like to have a list of all schemas with the fields definitions, not just module names. Can we get it and if yes then how, does ecto provide such api?

Kandykane answered 14/3, 2019 at 9:45 Comment(0)
T
9

According to Ecto.Schema's documentation,

Any schema module will generate the __schema__ function that can be used for runtime introspection of the schema.

You can use this together with Erlang's and Elixir's own introspection facilities for filtering all relevant modules and neatly retrieving details of any defined schemata, e.g.:

{:ok, modules} = :application.get_key(:your_app, :modules)

modules 
|> Enum.filter(&({:__schema__, 1} in &1.__info__(:functions))) 
|> Enum.each(&(IO.inspect(&1.__schema__(:fields))))
Tm answered 14/3, 2019 at 13:36 Comment(1)
Thanks, Vadim! Exactly what I needed.Kandykane

© 2022 - 2024 — McMap. All rights reserved.