Erlang:如何定义配置文件变量?

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

我是Erlang的新手,我对.config文件有疑问:我有一个配置文件:

{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.