elixir config 简单说明

发布时间 2024-01-04 17:32:43作者: 荣锋亮

elixir 的config 模块,实际上就是标准的方法,只是mix 项目中在使用的时候使用了dsl 模式的,没有使用包含括号的模式调用
给人一种似乎觉得有点怪的调用模式

参考代码

只说明config 方法,实际上Config 模块还包含了其他方法

  • mix 中的调用
 
import Config
 
config :ecto_demo, Dalong.App,
  database: "postgres",
  username: "postgres",
  password: "dalongdemo",
  hostname: "localhost"
 
 

实际上调用是config(root_key, key, opts) 这个方法

  • Config 模块部分参考源码
  def config(root_key, opts) when is_atom(root_key) and is_list(opts) do
    unless Keyword.keyword?(opts) do
      raise ArgumentError, "config/2 expected a keyword list, got: #{inspect(opts)}"
    end
 
    get_config!()
    |> __merge__([{root_key, opts}])
    |> put_config()
  end
 
  def config(root_key, key, opts) when is_atom(root_key) and is_atom(key) do
    get_config!()
    |> __merge__([{root_key, [{key, opts}]}])
    |> put_config()
  end
  • 使用方法模式调用
    实际上与上边的效果是一样的,只是不太符合elixir 元编程以及dsl 的玩法
 
import Config
 
# config :ecto_demo, Dalong.App,
#   database: "postgres",
#   username: "postgres",
#   password: "dalongdemo",
#   hostname: "localhost"
 
config(:ecto_demo,Dalong.App,[
  database: "postgres",
  username: "postgres",
  password: "dalongdemo",
  hostname: "localhost"
])

说明

对于elixir 如果碰到比较怪异或者开不太明白的方法调用(或者dsl 写法)最好的方法还是看源码以及官方文档,好多三方模块都使用了不少的
元编程玩法(macro ,behaviour 以及elixir 一些自身的语法特性)

参考资料

https://hexdocs.pm/elixir/main/Config.html
https://github.com/elixir-lang/elixir/blob/main/lib/elixir/lib/config.ex