Skip to content

Commit 4596baa

Browse files
henrikJosé Valim
authored andcommitted
Add IEx.Helpers.import_if_available/2 (#4877)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
1 parent c065041 commit 4596baa

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/iex/lib/iex/helpers.ex

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,25 @@ defmodule IEx.Helpers do
585585
raise ArgumentError, "import_file/1 expects a literal binary as its argument"
586586
end
587587

588+
@doc """
589+
Calls `import/2` with the given arguments, but only if the module is available.
590+
591+
This lets you put imports in `.iex.exs` files (including `~/.iex.exs`) without
592+
getting compile errors if you open a console where the module is not available.
593+
594+
## Example
595+
596+
# In ~/.iex.exs
597+
import_if_available Ecto.Query
598+
"""
599+
defmacro import_if_available(quoted_module, opts \\ []) do
600+
module = Macro.expand(quoted_module, __CALLER__)
601+
602+
if Code.ensure_loaded?(module) do
603+
quote do: import unquote(quoted_module), unquote(opts)
604+
end
605+
end
606+
588607
# Compiles and loads an Erlang source file, returns {module, binary}
589608
defp compile_erlang(source) do
590609
source = Path.relative_to_cwd(source) |> String.to_charlist

lib/iex/test/iex/helpers_test.exs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,12 @@ defmodule IEx.HelpersTest do
264264
assert failing =~ "no such file or directory"
265265
end
266266

267+
test "import_if_available helper" do
268+
assert "nil" == capture_iex("import_if_available NoSuchModule")
269+
assert "[1, 2, 3]" == capture_iex("import_if_available Integer; digits 123")
270+
assert "[1, 2, 3]" == capture_iex("import_if_available Integer, only: [digits: 1]; digits 123")
271+
end
272+
267273
test "c helper" do
268274
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->
269275
Sample.run

0 commit comments

Comments
 (0)