where is my priv_dir?

by David Weldon

Let’s say you’re writing an application that needs to load a file from its priv directory, so you need know its path. You just call code:priv_dir/1 with the name of your application right? Maybe. The catch is that this function only succeeds if your application is in the code path. As far as I’m able to tell that leaves us with three choices:

1) Make sure your application is installed to somewhere under a directory in $ERL_LIBS. This makes sense for a shared library, but may not make sense for your web server. Furthermore, when working on the code it’s annoying to have to add your development directory to $ERL_LIBS.
2) Just write code like file:read_file("./priv/dictionary"). Unfortunately that will only work if you run it from the application directory. Fail.
3) Use the following code:

{ModPath, _} = filename:find_src(?MODULE),
AppPath = filename:dirname(filename:dirname(ModPath)),
filename:join(AppPath, "priv").

So far that seems to be the winning solution for me. If you have a better solution or you can think of a reason why this doesn’t work please let me know.

Advertisements