Include Arbitrary Files in Elixir Project
There might be occasions in which we would want to include arbitrary files in our Elixir projects. Maybe we need to include executable. Or perhaps we’re building some kind of renderer and need some assets.
Such files should go in the optional
priv/ directory in the project root.
Assets placed here will be available during the application runtime.
Executables are supposed to go in
the Erlang application docs
for more details.
Accessing Files in
priv/ at Runtime
Let’s say you have
priv/my_file.txt and need to access it during the
application’s runtime. We can do so with the following code:
Escripts do not support loading artifacts in the
priv/ directory at runtime.
To work around this issue, we can store the file or file contents in a module
attribute at compile time, as Jose Valim explains in
this ElixirForm post.
Here’s an example:
defmodule SomeModule do @my_file_contents File.read! "priv/my_file.txt" def my_file_contents, do: @my_file_contents end
Now, when we compile our project we’ll have the contents of
stored in the module attribute
@my_file_contents which is accessible in escripts.