Dynamically reference a module spec

I have a module for each model in my program, and I can query them dynamically:

model = String.to_existing_atom( "Elixir." <> data.params.model )
query = from m in model,
  where: m.domain == ^data.payload.domain,
  select: %{
    :id => m.id,
    :date => m.date,
    :domain => m.domain
  }
result = Cc.MySQL.one(query)

where:

  1. data.params.model is CC.Mpesa.Woo.Model, set earlier in the program from constants
  2. query is using import Ecto.Query, only: [from: 2]

This works with no issue.

My question, now, is how to reference a module spec dynamically.

If I statically set the spec:

with {:ok, add} <- Cc.MySQL.insert %CC.Mpesa.Woo.Model{
  date: today,
  domain: data.payload.domain,
  agent: agent,
  key: @tools.makeid,
} do

The data will be inserted.

However I get an error when I place model here instead:

with {:ok, add} <- Cc.MySQL.insert %model{
  date: today,
  domain: data.payload.domain,
  agent: agent,
  key: @tools.makeid,
} do

Error:

    error: expected struct name to be a compile time atom or alias, got: model
    β”‚
 32 β”‚       with {:ok, add} <- Cc.MySQL.insert %model{
    β”‚                                          ^

How would I insert model as an atom here, so that the spec (schema) is used?

struct!(model, date: today, ...)

Don’t use this. Use that instead:

model = Module.concat([data.params.model])

Notice that the function argument is a list with a single item inside.

3 Likes