DEV Community

Cover image for How to include static assets in an Elixir application
Adam Davis
Adam Davis

Posted on • Originally published at brewinstallbuzzwords.com

How to include static assets in an Elixir application

tl;dr

  • Put your static assets in the /priv directory.
  • Identify the atom for your app in mix.exs. In this example, we’ll use :my_app.
  • Get the file path by using Application.app_dir/2.
  • Read the file according to your project’s needs. One way is with File.stream!/3.

Example:

def get_my_file_stream() do
  Application.app_dir(:my_app, "/priv/my_file.txt")
  |> File.stream!()
end
Enter fullscreen mode Exit fullscreen mode

Diving deeper

If the above info solved your problem, great! You can go ahead and close this page.

But if you want to learn more about this topic, keep reading.

The legacy of OTP

The Elixir programming language is built on top of Erlang/OTP. If you don’t know about Erlang/OTP, check out this page from the Erlang FAQ.

Within Erlang/OTP applications, there is a standard directory structure, which looks like this:

─ ${application}
    ├── doc
    │   ├── internal
    │   ├── examples
    │   └── src
    ├── include
    ├── priv
    ├── src
    │   └── ${application}.app.src
    └── test
Enter fullscreen mode Exit fullscreen mode

The proper directory for storing static assets in these applications is /priv, and Elixir inherits this structure.

If you’d like to see more details on Erlang/OTP applications, check out this page in the OTP Design Principles User’s Guide.

Leveraging the Erlang :code module

Although we used Application.app_dir above, that’s not the only way to get the file path.

Another approach would be to use the Erlang :code module, which you can call directly from your Elixir code (docs here).

The :code module has a function called priv_dir/1 which will return the path to the priv directory for the given application (docs here). Then, you can get the complete path for your file using Path.join/2.

def get_my_file_stream() do
  :code.prive_dir(:my_app)
  |> Path.join("my_file.txt")
  |> File.stream!()
end
Enter fullscreen mode Exit fullscreen mode

More content

If you liked this, you might also like some of my other posts. If you want to be notified of my new posts, follow me on Dev or subscribe to my brief monthly newsletter.

Top comments (0)