Skip to content

Instantly share code, notes, and snippets.

@hoangbits
Created July 21, 2021 02:17
Show Gist options
  • Save hoangbits/8bbcc47ca05f187dfd0343804708c6a0 to your computer and use it in GitHub Desktop.
Save hoangbits/8bbcc47ca05f187dfd0343804708c6a0 to your computer and use it in GitHub Desktop.
defmodule ModuleToBeUsed do
defmacro __using__(_) do
IO.puts __MODULE__ # COMPILATION STAGE
quote do # needed to prevent execution on compilation stage
IO.inspect(__MODULE__, label: "__MODULE__")
IO.inspect(unquote(__MODULE__), label: "unquote(__MODULE__)")
import unquote(__MODULE__)
def test, do: IO.puts "I am test" # EXECUTION STAGE
end
end
end
defmodule ModuleUsing do
use ModuleToBeUsed
def test_of_test, do: test() # I can call `test` here!
end
ModuleUsing.test_of_test()
####### output ########
# Elixir.ModuleToBeUsed
# __MODULE__: ModuleUsing
# unquote(__MODULE__): ModuleToBeUsed
# I am test
@hoangbits
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment