Sebb

Sebb

Load json into struct in module-attribute

I want to load a json (list of objects) into list of structs in a module attribute.
Seems like I need three modules for that.

json

[
    {"foo": 1, "bar": 2},
    {"foo": 11, "bar": 22}
]

struct

defmodule Foo do
  defstruct [:foo, :bar]
end

load into struct, note that function in reality is too complex to be added to Foos/@foos - pipe

defmodule JsonLoader do
  def load_foos(foos) do
    Enum.map(foos, &struct(Foo, &1))
  end
end

module that stores the structs in a module attribute.

defmodule Foos do
  @foos File.read!("lib/foos.json") |> Jason.decode!(keys: :atoms) |> JsonLoader.load_foos()

  def get_foo(foo) do
    Enum.find(@foos, fn f -> f.foo == foo end)
  end
end

Is there way to bring all that into one module (Foo).

Marked As Solved

LostKobrakai

LostKobrakai

There is not. You can neither execute functions of a module within its own module body nor create structs of the to be compiled module at compile time. Both the struct definition as well as the function will only be available once the module is fully compiled. At the time you provide the module attribute value the module is still being compiled.

The best you can do is 2 modules. One for the struct and one with the module attribute, by inlining the code of load_foos.

Also Liked

aziz

aziz

I’d like to challenge that claim. :grinning_face_with_smiling_eyes:

defmodule Foo do
  defstruct [:foo, :bar]

  @foos File.read!("lib/foos.json")
        |> Jason.decode!(keys: :atoms)
        |> Enum.map(&Map.put(&1, :__struct__, __MODULE__))

  def list do
    @foos
  end

  def equal? do
    @foos == [%Foo{bar: 2, foo: 1}, %Foo{bar: 22, foo: 11}]
  end
end

Foo.list() |> IO.inspect(label: "list()")
Foo.equal?() |> IO.inspect(label: "equal?()")

So you can’t use the struct function but that’s a small price to pay if you really want/need to do this. :wink:

LostKobrakai

LostKobrakai

The first is just a dump alias for the current module name. The second is creating a struct, which does do things like checking keys, and such, which does fail without the struct being defined.

&Map.put(&1, :__struct__, __MODULE__) just uses knowledge about implementation details of structs to construct them without doing all the consistency checks structs have when being constructed otherwise.

Last Post!

LostKobrakai

LostKobrakai

The first is just a dump alias for the current module name. The second is creating a struct, which does do things like checking keys, and such, which does fail without the struct being defined.

&Map.put(&1, :__struct__, __MODULE__) just uses knowledge about implementation details of structs to construct them without doing all the consistency checks structs have when being constructed otherwise.

Where Next?

Popular in Questions Top

vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130579 1222
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement