[erlang-questions] sharing config via a dynamically compiled module?

Benoit Chesneau bchesneau@REDACTED
Wed Oct 25 15:27:17 CEST 2017



> On 25 Oct 2017, at 15:04, Roger Lipscombe <roger@REDACTED> wrote:
> 
> On 25 October 2017 at 13:29, Benoit Chesneau <bchesneau@REDACTED> wrote:
>> I'm temped to compile dynamically a module for some highly demanded resources
>> to share their config instead of using ETS for it. But I'm wondering if's not
>> to hackish. (I'm also tempted by just using something more pure like sharing it
>> via message passing).
>> 
>> Are other people do such thing?
> 
> Yes: https://github.com/mochi/mochiweb/blob/master/src/mochiglobal.erl <https://github.com/mochi/mochiweb/blob/master/src/mochiglobal.erl>


Indeed :) I’ve also somewhat simpler code:

-include_lib("syntax_tools/include/merl.hrl").

%% @doc Utility that converts a given property list into a module that provides
%% constant time access to the various key/value pairs.
%%
%% Example:
%%
%%   load_config(store_config, [{backends, [{rocksdb_ram, barrel_rocksdb},
%%                                          {rocksdb_disk, barrel_rocksdb}]},
%%                              {data_dir, "/path/to_datadir"}]).
%%
%% creates the module store_config:
%%   store_config:backends(). => [{rocksdb_ram,barrel_rocksdb},{rocksdb_disk,barrel_rocksdb}]
%%   store_config:data_dir => "/path/to_datadir"
%%
-spec load_config(atom(), [{atom(), any()}]) -> ok.
load_config(Resource, Config) when is_atom(Resource), is_list(Config) ->
  Module = ?Q("-module(" ++ atom_to_list(Resource) ++ ")."),
  Functions = lists:foldl(fun({K, V}, Acc) ->
                              [make_function(K,V) | Acc]
                          end,
                          [], Config),
  Exported = [?Q("-export([" ++ atom_to_list(K) ++ "/0]).") || {K, _V} <- Config],
  Forms = lists:flatten([Module, Exported, Functions]),
  merl:compile_and_load(Forms, [verbose]),
  ok.

make_function(K, V) ->
  Cs = [?Q("() -> _@REDACTED@")],
  F = erl_syntax:function(merl:term(K), Cs),
  ?Q("'@_F'() -> [].").

%% @doc unload a config module loaded with the `load_config/2' function.
-spec unload_config(atom()) -> true | false.
unload_config(Resource) ->
  _ = code:purge(Resource),
  code:delete(Resource).

which is doing something similar but create a function for each keys in the proplists. But I’m  wondering if there are some cons to it apart the fact it is designed for case where little changes happen to the conf . It seems lot of people are using ets to share a config generally. Maybe becauseit feels a little hackish ?

- benoit
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20171025/29849fcf/attachment.htm>


More information about the erlang-questions mailing list