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)

Need better DEV posts?

You can set your approximate experience level in settings which can help improve the relevance of your DEV Home Feed.