:code.priv_dir at compile time and releases

say I have a module attribute like

@priv :code.priv_dir(:my_app)

or sth else that gets compiled, like

~H"""<%= :code.priv_dir(:my_app) %>"""

This all works fine but if you mix release the priv-dir changes and the path becomes invalid.
What do? Where to put my files?

What I actually do is load some css from priv like

<%= Phoenix.HTML.raw(:code.priv_dir(:my_app) ++ '/css/style.css') %>

Don’t do it at compile-time, do it inside a function. :slight_smile:

FWIW <%= inside ~H is not done at compile-time.

2 Likes

indeed, I was just being stupid. So the problem is solved :crazy_face:

1 Like

I need to bring this back. I’m trying to get a file form priv directory in the config.exs file. But still getting {:error, :bad_name}.

metadata_file: "#{:code.priv_dir(:my_app)}/my_file"

Can someone please help me since I can’t create function for configs

It is not possible to use :code.priv_dir in config, because the application is not yet compiled.

1 Like

I got it, I’m trying to use this instead.

Application.app_dir(:my_app) <> "/priv/cert/my_file"
1 Like

Be really careful about compiling the result of :code.priv_dir or hardcoding the path. I’ve been burned by it before when building on a separate host as the target. I can’t remember the exact issue but it boiled down to it compiling a path on the build machine that didn’t exist on the target machine. Sorry I can’t remember the exact details as it was over a year ago.

You can also use closures as config values.

config, :my_app, metadata_file: fn -> "#{:code.priv_dir(:my_app)}/my_file" end

Application.get_env(:my_app, :metadata_file).()

It’s not always ideal, but it works. I’ve never done it with :code.priv_dir myself, though, so not sure about that one. I’m not sure about using :code in a running system in general, though.

2 Likes

I am curious about that part, why you are not sure about using :code Erlang’s module in a running system?

Oh sorry I forgot about this—yes it’s fine. You know when you’re trying to remember why something went wrong and you start to doubt everything? It’s definitely ok in a running system—I have it in a few places.

2 Likes