如何定义配置文件变量?

问题描述 投票:3回答:1

我有一个配置文件,带有:

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

路径和名称可以由用户更改。据我所知,有一种方法可以通过使用

中的file:consult/1将这些变量保存在模块中
-define(VARIABLE, <parsing of the config file>).

有什么更好的方法可以在模块开始工作时读取配置文件,而无需在-define中创建解析功能? (据我所知,根据Erlang开发人员的说法,这不是在-define中制作复杂函数的最佳方法)

configuration erlang otp
1个回答
4
投票

如果仅在启动应用程序时需要存储配置-您可以使用在'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"}]
     }]
  }
]}.

关于此的更多信息:rebar3 configuration

下一步创建yourapplication.config-将其存储在应用程序文件夹/app/config/local/yourapplication.config

此配置应具有类似于此示例的结构

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

所以当您的应用程序启动时您可以使用

获得整个配置数据
{ok, "/mnt/test/"} = application:get_env(yourapplicationname, path)
{ok, "Joe"} = application:get_env(yourapplicationname, name)

现在您可以-定义此变量,例如:

-define(VARIABLE,
    case application:get_env(yourapplicationname, path) of
        {ok, Data} -> Data
        _   -> undefined
    end
).
© www.soinside.com 2019 - 2024. All rights reserved.