What is a usual way of storing and loading resource file in Erlang. I need to create a certain human-readable dictionary and load it at application initialization. For example, in Java I would put the data in a .property file, then put it somewhere in the classpath and finally load it with help of code like this:
new Properties().load(Class.getResourceAsStream("/file.properties"))
So, I have the following questions:
- where I can (must) keep the resource file?
- how to determine in runtime the path to the resource file
- how to load it (for example
file:consult(Filename)
)
In Erlang properties are in *.config file, that usually is (but doesn't have to be) in the root directory of your project. For example:
- Chicago Boss has boss.config
- RabbitMQ has rabbitmq.config
- Zotonic has different configs for different sites stored in priv/sitename/config
You can provide config file by running
erl -config myconfig
WARNING: the file should be named "myconfig.config" and you should omit the extension.
The config file should be structured this way:
[{Application1, [{Par11,Val11},...]},
...,
{ApplicationN, [{ParN1,ValN1},...]}].
for example:
[{kernel, [
{my_key, "value"}
]}].
Than in erlang shell, you can type:
application:get_env(kernel, my_key).
{ok,"value"}
I used kernel application, because it is always loaded and application:get_env/2 returns undefined, if the application is not loaded. You should put any configs in your own application and make sure, that it is loaded before invoking get_env/2.
Also, configs are hierarchical, you can put the defaults in *.app file, that user usually doesn't have to modify. You can overwrite them in config file and finally, you can provide the key value pairs in command line (they will overwrite things, that are in config file).
You can read more about configuration here:
http://www.erlang.org/doc/design_principles/applications.html#id74398
You can also make config file more user friendly by using comments, example:
https://github.com/ChicagoBoss/ChicagoBoss/blob/master/skel/boss.config
I found the answer myself. The prefered path to store resource files is a priv
directory. code:priv_dir/1
returns the path to the priv
directory in an application.
Here is a code snippet to load JSON from the file:
File = filename:join([code:priv_dir(application), "resource.json"]),
{ok, Text} = file:read_file(File),
%% parse json