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

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
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
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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

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
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
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

We're in Beta

About us Mission Statement