Is there a way to let Elixir write this code for me?

Hi,

I have an embedded_schema in my application, and I need fields with numbers as names, where those numbers are like Enum.to_list(1..30).

When writing the schema, it will look like this:

@numbers Enum.to_list(1..30)

embedded_schema do
  field :"1"
  field :"2"
  field :"3"
  field :"4"
  # ...
  field :"29"
  field :"30"
end

Is there a way to let Elixir loop through my @numbers and write something like

field (number |> Integer.to_string |> String.to_atom)

automatically?

(Btw, it might seem strange to have such a schema, but I’ve tried quite a lot of shapes and this one is the nicest to deal with. Also, in my use case every number in the schema refers to a specific thing, so it makes sense :slight_smile:)

1 Like

I think this will work. Note that I have not tested it.

for i <- (1..30) do
  i_sym = i
    |> Integer.to_string
    |> String.to_atom
  quote do
    field unquote(i_sym)
  end
end
2 Likes

Something like this should also work:

schema "foo" do
  for i <- 1..30 do
    field :"#{i}"
  end
end
4 Likes

Strange, I’m sure that’s the first thing I tried :smile:
Thanks @michalmuskala and @Qqwy!

1 Like