New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Struct default values random behaviour when using env var #3289
Comments
This behavior is going to read the application configuration at compile José Valim |
I don't know if I'm right, please correct me if not, I believe the struct default values are evaluated only once, when the struct is evaluated. In this case I think that the application configuration should be available so that the struct can receive its default values. One use case for this is when I need to authenticate to an third party web service and want to have my authentication info in a struct without having to set it everytime. For instance, I can build the request like: request = %Request{
auth: %Auth{},
foo: "bar"
} Where defstruct key: Application.get_env(:app, :key), secret: Application.get_env(:app, :secret) |
Struct default values are evaluated only once - at compile time. If you have the key and secret when compiling you should be fine, if not you need to fetch it every time you create a struct. |
I could not reproduce this. The values are always there if they have been set at compilation time. |
I'm sorry, I've not shown you the full scenario. This behaviour happen when I have this struct in a project and I try to configure it from another project. Say I have the project I think there should be a warning in the docs to tell people about this. It is documented here though, in case someone else runs in the same problem. |
Your approach is fine but you need to configure it before you add A as a dependency. If it is done afterwards, you should do |
I have the following scenario where a struct is defined with default values that come from
Application.get_env
function:These env values come from the
config.exs
as follows:Sometimes when the application starts, the struct receives the values from the config, sometimes it just receives
nil
, actually, most of the time it receivesnil
.I think that this happens because the configuration is being evaluated after the struct definition, then when it tries to get the values they weren't defined yet.
The text was updated successfully, but these errors were encountered: