ngeraedts

ngeraedts

Conditional import fails to compile

I’m trying to import a helper module in my application that is only available in under :dev and :test mix environments.

I’ve got the following in my mix.exs to prevent the helper module from being compiled under :prod:

  defp elixirc_paths(:test), do: ["lib", "test/fixtures", "test/support"]
  defp elixirc_paths(:dev), do: ["lib", "test/fixtures"]
  defp elixirc_paths(_), do: ["lib"]

and then the following in the body of one of my modules:

def MyAppWeb.ProxyController do
  ...
  # Insert controller actions to serve fixture data in development and testing
  if Mix.env() in [:dev, :test] do
    import MyApp.Fixtures, only: [mock_proxy: 1]

    mock_proxy(:the_thing)
  end
  ...
end

The mock_proxy/1 macro injects some function clauses to the module. This works great under :dev or :test environments, but fails in :prod with the following error?

== Compilation error in file lib/my_app_web/controllers/proxy_controller.ex ==
** (CompileError) lib/my_app_web/controllers/proxy_controller.ex:18: module MyApp.Fixtures is not loaded and could not be found
    (stdlib 3.14.2) lists.erl:1358: :lists.mapfoldl/3
    (stdlib 3.14.2) lists.erl:1359: :lists.mapfoldl/3
    (elixir 1.12.1) expanding macro: Kernel.if/2

I thought this wouldn’t happen because of the if statement at the module level, but clearly something else is going on. I can “fix” this by compiling this path in all environments, but I’d like to avoid that if I can.

Any thoughts on what I’m missing here?

Marked As Solved

aziz

aziz

The code needs to be put in a macro which can return something depending on a condition. I was able to make the following work:

defmodule Compile do
  defmacro only_in(envs, body) do
    if Mix.env() == envs or Mix.env() in envs do
      body
    end
  end
end

def MyAppWeb.ProxyController do
  require Compile

  Compile.only_in [:dev, :test] do
    import MyApp.Fixtures, only: [mock_proxy: 1]
    mock_proxy(:the_thing)
  end
end

This is just a suggestion. Maybe there’s a better way but this should help you to make progress for now. :+1:

Also Liked

aziz

aziz

Here is an improved version that allows an optional else-body:

defmodule Compile do
  defmacro only_in(envs, body) do
    if Mix.env() in List.wrap(envs) do
      body[:do]
    else
      body[:else]
    end
  end
end

def MyAppWeb.ProxyController do
  require Compile

  Compile.only_in [:dev, :test] do
    import MyApp.Fixtures, only: [mock_proxy: 1]
    mock_proxy(:the_thing)
  else
    IO.puts("No mock for prod.")
  end
end
josevalim

josevalim

Creator of Elixir

Correct! The code in “if” won’t be executed but it still has to be expanded, hence the failure.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

We're in Beta

About us Mission Statement