Ensure struct was compiled
I am facing the issue that I get a :non_struct error, when trying to convert my map to a struct. It seems like this happens when the Module was not loaded before.
iex(1)> Maptu.struct(MyStruct, %{}) # does not work
{:error, {:non_struct, MyStruct}}
iex(2)> %MyStruct{}
%MyStruct{name: "", url: ""}
iex(3)> Maptu.struct(MyStruct, %{}) # now it works
{:ok, %MyStruct{name: "", url: ""}}
So I added a Code.ensure_compiled?(mod) check to ensure the module is loaded.
My System: Erlang/OTP 19 Elixir (1.4.2)
Hey @bitecodes, we're not sure this is a good idea. Loading a module is an expensive-ish operation and it's likely the responsibility of the user to ensure that modules they're going to use are loaded. In any way we definitely think the documentation needs to be improved to mention that modules are not loaded by Maptu and we will also improve the error message to say :module_not_loaded (or something similar) instead of :bad_struct.
Out of curiosity, how did you get in a state where MyStruct wasn't loaded? Do you have a reproducible case?
Hi @whatyouhide,
maybe I am doing something wrong then that causes my module not to be loaded. So far I haven't had any issues with Modules being not loaded, but then again I don't have a lot of experience in Elixir.
I have created an app to reproduce this issue: https://github.com/bitecodes/maptu_app
Running the app gives me the following output
iex -S mix
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.4.2) - press Ctrl+C to exit (type h() ENTER for help)
{:error, {:non_struct, MaptuApp.MyStruct}}
iex(1)>
13:12:49.413 [info] Application maptu_app exited: normal
iex(2)> Maptu.struct(MaptuApp.MyStruct, %{})
{:error, {:non_struct, MaptuApp.MyStruct}}
iex(3)> Maptu.struct(MaptuApp.MyStruct, %{})
{:error, {:non_struct, MaptuApp.MyStruct}}
iex(4)> c "lib/my_struct.ex" # My understanding is that the Module was loaded before?
warning: redefining module MaptuApp.MyStruct (current version loaded from _build/dev/lib/maptu_app/ebin/Elixir.MaptuApp.MyStruct.beam)
lib/my_struct.ex:1
[MaptuApp.MyStruct]
iex(5)> Maptu.struct(MaptuApp.MyStruct, %{})
{:ok, %MaptuApp.MyStruct{body: nil, title: nil}}
@bitecodes this looks like an Elixir bug to me. If you try mix clean and run iex -S mix again, it works for me, then when I run it again, it doesn't load the module. Then again by cleaning it's loaded. 🤔
I just came across this problem too (Elixir 1.5.1). If iex starts up without doing any compiling, then the module doesn't seem to get loaded. The docs for function_exported? mention this. I can work around by doing Code.ensure_loaded before Maptu.struct!, but seems a bit hacky.