【问题标题】:Can't access a dependency config in main elixir project无法访问主 elixir 项目中的依赖项配置
【发布时间】:2018-11-04 23:17:47
【问题描述】:

我有一个项目 world_app 作为依赖项包含在 hello_app 中(如果相关,我已将其作为本地依赖项包含)

defp deps do
  [
    {:world_app, path: "../world_app"}
  ]
end

world_app 有一个具有此配置的 config.exs

config :world_app, some_config: "config_string"

当我尝试在 hello_app 中获取 world_app 中定义的配置变量时出现了我的问题(我在 hello_app 中运行 iex -S mix)

iex(1)> Application.get_all_env(:world_app)
[included_applications: []]

iex(2)> Application.get_env(:world_app, :some_config)
nil

但是,当我在 world_app 中执行相同操作时,我可以看到变量

iex(1)> Application.get_all_env(:world_app)
[some_config: "config_string", included_applications: []]

iex(2)> Application.get_env(:world_app, :some_config)
"config_string"

我一直认为我可以从父应用程序访问依赖项的配置;我在这里遗漏了什么重要的东西吗?

我正在使用 Elixir 1.5.3 和 erlang 20

【问题讨论】:

    标签: elixir elixir-mix


    【解决方案1】:

    依赖项的配置不会自动导入。在umbrella projects 中,所有的孩子都可以看到彼此的配置,因为根配置包含这条神奇的线:

    import_config "../apps/*/config/config.exs"
    

    它导入其所有子级的所有配置文件,相反,它的所有子级都指向mix.exs中的根配置文件:

    defmodule ChildProject.MixProject do
      use Mix.Project
    
      def project do
        [
          (...)
          config_path: "../../config/config.exs",
          (...)
        ]
      end
    
      (...)
    
    end
    

    chapter of the Mix & OTP Getting Started Guide 对此有所解释。


    您可以使用相同的技巧通过将此行添加到hello_app/config/config.exs 来显式导入依赖项的配置:

    import_config "../../world_app/config/config.exs"
    

    【讨论】:

    • 这对我帮助很大,谢谢你知道的越多
    【解决方案2】:

    作为 Zoltán 答案的更新,如果您在 documentation 中使用 Config 而不是 Mix.Config,则说明:

    确保您的 import_config/1 调用没有通配符。 如果是这样,您需要手动执行通配符查找。例如, 如果你这样做了:

    import_config "../apps/*/config/config.exs"
    

    它必须被替换为:

    for config <- "../apps/*/config/config.exs" |> Path.expand(__DIR__) |> Path.wildcard() do
          import_config config
        end
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2013-01-24
      • 2017-01-23
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多