Add IEx.Helpers.use_if_available/2 (#7254)

This commit is contained in:
Wojtek Mach
2018-01-24 21:18:04 +01:00
committed by José Valim
parent 106efa2ace
commit 1fcc16f346
2 changed files with 31 additions and 0 deletions
+23
View File
@@ -1052,6 +1052,29 @@ defmodule IEx.Helpers do
end
end
@doc """
Calls `use/2` with the given arguments, but only if the module is available.
This lets you use the module in `.iex.exs` files (including `~/.iex.exs`) without
getting compile errors if you open a console where the module is not available.
## Example
# In ~/.iex.exs
use_if_available Phoenix.HTML
"""
@since "1.7.0"
defmacro use_if_available(quoted_module, opts \\ []) do
module = Macro.expand(quoted_module, __CALLER__)
if Code.ensure_loaded?(module) do
quote do
use unquote(quoted_module), unquote(opts)
end
end
end
defp compile_elixir(exs, :in_memory), do: Kernel.ParallelCompiler.compile(exs)
defp compile_elixir(exs, path), do: Kernel.ParallelCompiler.compile_to_path(exs, path)
+8
View File
@@ -732,6 +732,14 @@ defmodule IEx.HelpersTest do
end
end
describe "use_if_available" do
test "uses a module only if available" do
assert "nil" == capture_iex("use_if_available NoSuchModule")
assert "1" == capture_iex("use_if_available Bitwise; 1 &&& 1")
assert "1" == capture_iex("use_if_available Bitwise, only_operators: true; 1 &&& 1")
end
end
describe "c" do
test "compiles a file" do
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->