Managing configuration in Erlang application

前端 未结 5 1597
日久生厌
日久生厌 2020-12-23 17:50

I need to distribute some sort of static configuration through my application. What is the best practice to do that?

I see three options:

  1. Call ap
5条回答
  •  生来不讨喜
    2020-12-23 18:32

    You could use a process (a gen_server maybe?) to store your configuration parameters in its state. It should expose a get/set interface. If a value hasn't been explicitly set, it should retrieve a default value.

    -export([get/1, set/2]).
    
    ...
    
    get(Param) ->
      gen_server:call(?MODULE, {get, Param}).
    
    ...
    
    handle_call({get, Param}, _From, State) ->
      case lookup(Param, State#state.params) of
        undefined ->
          application:get_env(...);
        Value ->
          {ok, Value}
      end.
    
    ...
    

    You could then easily mockup this module in your tests. It will also be easy to update the process with some new configuration at run-time.

    You could use pattern matching and tuples to associate different configuration parameters to different modules:

    set({ModuleName, ParamName}, Value) ->
      ...
    
    get({ModuleName, ParamName}) ->
      ...
    

    Put the process under a supervision tree, so it's started before all the other processes which are going to need the configuration.

    Oh, I'm glad nobody suggested parametrized modules so far :)

提交回复
热议问题