Added module to handle configuration files
authorMatt Mullins <mmullins@mmlx.us>
Sat, 21 May 2011 22:53:25 +0000 (17:53 -0500)
committerMatt Mullins <mmullins@mmlx.us>
Sat, 21 May 2011 22:53:25 +0000 (17:53 -0500)
core/config.erl [new file with mode: 0644]

diff --git a/core/config.erl b/core/config.erl
new file mode 100644 (file)
index 0000000..58f0b89
--- /dev/null
@@ -0,0 +1,50 @@
+%% @doc Looks up information in the configuration file.
+%% This restructs us to a configuration file that contains multiple terms of
+%% the form:
+%%     {Tag, Data}.
+%%
+%% TODO: I might, at some point in the future, want to throw an instance name
+%% in each of the terms in the configuration file, but for now, this is fine.
+
+-module(config).
+-behavior(gen_server).
+
+% Public-facing functions
+-export([start_link/0,
+         get_config/1]).
+% Call-backs for gen_server
+-export([init/1, handle_call/3]).
+
+-record(config_state, {filename, data}).
+
+% Public-facing functions
+start_link() ->
+    gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
+
+%% @doc Looks up the given Tag in the configuration file.
+%% Returns [Data], where Data is the data included in each mention of Tag in
+%% the configuration file.
+get_config(Tag) ->
+    gen_server:call(?MODULE, {get_config, Tag}).
+
+% Callbacks and process internals
+init(_) ->
+    Filename = get_filename(),
+    {ok, Data} = file:consult(Filename),
+    {ok, #config_state{filename = Filename, data = Data}}.
+
+%% @doc Looks up the given Tag in the configuration file
+%% Returns [Data], where the Data is whatever was in each of the appropriate
+%% terms in the configuration file.
+handle_call({get_config, Tag}, _From, State = #config_state{data = Data}) ->
+    Terms = lists:filter(fun ({ConfTag, _}) -> Tag == ConfTag end, Data),
+    Return = lists:map(fun ({_, ConfData}) -> ConfData end, Terms),
+    {reply, Return, State}.
+
+%% @doc Gets the name of the configuration file, either from the -bot_config
+%% command-line parameter, or returns "bot.cfg" as a fall-back.
+get_filename() ->
+    case init:get_argument(bot_config) of
+        {ok, [[Filename]]} -> Filename;
+        _ -> "bot.cfg"
+    end.