Search code examples
configurationerlangerlang-otp

How to define config file variables?


I have a configuration file with:

{path, "/mnt/test/"}.
{name, "Joe"}.

The path and the name could be changed by a user. As I know, there is a way to save those variables in a module by usage of file:consult/1 in

-define(VARIABLE, <parsing of the config file>).

Are there any better ways to read a config file when the module begins to work without making a parsing function in -define? (As I know, according to Erlang developers, it's not the best way to make a complicated functions in -define)


Solution

  • If you need to store config only when you start the application - you may use application config file which is defined in 'rebar.config'

    {profiles, [
      {local,
        [{relx, [
          {dev_mode,      false},
          {include_erts,  true},
          {include_src,   false},
          {vm_args,       "config/local/vm.args"}]
          {sys_config,    "config/local/yourapplication.config"}]
         }]
      }
    ]}.
    

    more info about this here: rebar3 configuration

    next step to create yourapplication.config - store it in your application folder /app/config/local/yourapplication.config

    this configuration should have structure like this example

    [
        {
            yourapplicationname, [
                {path, "/mnt/test/"},
                {name, "Joe"}
            ]
        }
    ].
    

    so when your application is started you can get the whole config data with

    {ok, "/mnt/test/"} = application:get_env(yourapplicationname, path)
    {ok, "Joe"} = application:get_env(yourapplicationname, name)
    

    and now you may -define this variables like:

    -define(VARIABLE,
        case application:get_env(yourapplicationname, path) of
            {ok, Data} -> Data
            _   -> undefined
        end
    ).