elixir config 简单说明

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

posted on   荣锋亮  阅读(19)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2023-01-04 dremio DatasetSaver 服务说明
2023-01-04 dremio datastore简单说明
2023-01-04 piperider 开源数据可靠性工具
2022-01-04 census 安全处理模式
2022-01-04 castled 简单原理说明
2021-01-04 goja 支持es6的一种方法
2021-01-04 salesforce 跨组织数据可见性的方案

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示