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

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
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

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement