I am trying to understand bind_quoted in macro and have following macro module:
defmodule Debugger do
defmacro log(expression) do
if Application.get_env(:debugger, :log_level) == :debug do
quote bind_quoted: [expression: expression] do
IO.puts "============="
IO.inspect expression
IO.puts "============="
expression
end
else
expression
end
end
end
Then in the shell, I play around as follow with the module
iex(1)> import_file "debugger_fixed.exs"
{:module, Debugger,
<<70, 79, 82, 49, 0, 0, 6, 224, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 158, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
{:log, 1}}
iex(2)> require Debugger
nil
iex(3)> Application.put_env(:debugger, :log_level, :debug)
:ok
iex(4)> remote_api_call = fn -> IO.puts("calling remote API...") end
iex(7)> Debugger.log(remote_api_call.())
as the result on the last line, I’ve got
calling remote API...
=============
:ok
=============
:ok
but I expect
=============
calling remote API...
:ok
=============
:ok
I know that bind_quoted execute an expression only once.
My question is, can someone please explain why I’ve got unexpected result?
THanks