在Elixir中定义一个常量模块 [英] Define a constant module in elixir
问题描述
我想创建一些可变的边界模块.理想情况下,结果看起来像任何其他模块一样,但是可以在编译时或在配置文件中设置行为.我想我正在寻找类似erlang的东西
说我有一个SystemClock模块和一个DummyClock元组模块.理想情况下,时钟"模块应该是配置文件中上面选择的两个模块中的一个或另一个.
在config/test.ex
define(Clock, {DummyClock, 12345678})
以后
Clock.now
# => 12345678
在config/prod.ex
define(Clock, SystemClock)
以后
Clock.now
# => 32145687
我认为最简单的方法是使用configs和Application.get_env/2
.
config/test.exs
中
config :my_application, clock: DummyClock
config/dev.exs
和config/prod.exs
config :my_application, clock: RealClock
使用时钟的代码中
defp clock, do: Application.get_env(:my_application, :clock)
def my_function(arg1, arg2) do
now = clock.now
# ...
end
I would like to create some changeable boundary module. Ideally the result would look like any other module but the behaviour could be set at compile time or in the configuration files. I think I am looking for something like define in erlang
Say I have a SystemClock module and a DummyClock tuple module. Ideally the Clock module would be one or other of the two modules above chosen in the config file.
In config/test.ex
define(Clock, {DummyClock, 12345678})
Later
Clock.now
# => 12345678
In config/prod.ex
define(Clock, SystemClock)
Later
Clock.now
# => 32145687
I think the easiest way to do this is with configs and Application.get_env/2
.
in config/test.exs
config :my_application, clock: DummyClock
in config/dev.exs
and config/prod.exs
config :my_application, clock: RealClock
in the code that uses the clock
defp clock, do: Application.get_env(:my_application, :clock)
def my_function(arg1, arg2) do
now = clock.now
# ...
end
这篇关于在Elixir中定义一个常量模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!