I am trying to get better at Elixir and I was looking for a reason to make a library. Because writing libraries seem to be a good way to learn Elixir, not just doing code but actually implementing low level tech and seeing what they return. So I found myself wanting to take a map and create a struct from it. The function should also tolerate if any keys are missing or if there are more keys than whats specified. So i wrote this library.
It has a function that takes a keyword list or a map and converts into a struct given a module name.
Here is the link for anyone interested: https://github.com/smolcatgirl/struct_create
I would like any feedback Thank you!
Just in case, there is
Kernel.struct/2 for that.
As an exercise it’s nice! But you very likely don’t want to use this in production since it will cause an atom table leak if it’s passed user maps. This is a security regression as a malicious user can start spamming your server with strings that aren’t atoms yet and eventually cause your server to crash.
What if I change it to use String.to_existing_atom?
struct/2 fails if I include too many keys. I could filter the keys before but my library does it for me and it works with keyword lists too.
edit: wait it seems like i got it wrong, struct/2 works with this.
That’s slightly better but keep in mind that crashes the calling process. You should probably do a reverse check, which is to say, filter props in your proplist which don’t match Atom.to_string for the struct properties. Do you know how to obtain the list of fields in a struct?
Map.from_struct, Map.keys and then map them and convert them to strings?
Should I return a errror value in case the user provide a bad module name or a non keyword list or non map?
Yes. Also, modules with structs define a magic
__struct__/0 function that you can use to get a hold of the default struct, bypassing @enforce_keys requirements (use with caution).