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.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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

We're in Beta

About us Mission Statement