I am quit new to elixir coming from ruby, python, C or node.
What I try to do is to define a generic struct which has one static field ‘json’ with a json String as a value.
I want to define each key of that json object map to a function in the struct.
defmodule Models.Generic do
alias __MODULE__
defstruct json: {}
Map.keys(
Poison.Parser.parse!(json, %{keys: :atoms!})
|> Enum.each(fn name ->
def unquote(:"#{name}")() do
json[name]
end
end)
)
end
But I get
** (CompileError) lib/models/generic.ex:7: undefined function json/0
Can anyone explain what is happen here and how I can fulfill my use case, please?
I do not have a project at hands that uses :poison (well, my current machine doesn’t even have elixir installed), but the following should “just” work:
data = Poison.Parser.parse!(~s[{"foo": "bar"}], %{keys: :atoms!})
data.foo == "bar"
Can you talk more about your overall use case? What you’ve described is an implementation approach: building dynamic structs. This approach is not really feasible given how structs work. If you describe the overall problem you’re trying to solve though perhaps we can suggest alternative approaches.