Skip to content

Instantly share code, notes, and snippets.

@ejpcmac
Created July 1, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejpcmac/3aad916282ffd98a55ba5d77a2f6fc3e to your computer and use it in GitHub Desktop.
Save ejpcmac/3aad916282ffd98a55ba5d77a2f6fc3e to your computer and use it in GitHub Desktop.
Recursively defining fixtures
defmodule Fixtures do
def user do
quote do
def user, do: :user
end
end
def client do
quote do
# You can use fixtures recursively.
use Fixtures, [:user]
def client, do: user()
end
end
def apply_fixture(fixture) do
quote do
# Import the fixture only if it has not been imported previously.
unless unquote(fixture) in Module.get_attribute(__MODULE__, :fixtures) do
# Register the fixture import
Module.put_attribute(__MODULE__, :fixtures, unquote(fixture))
unquote(apply(__MODULE__, fixture, []))
end
end
end
defmacro __using__(fixtures) when is_list(fixtures) do
attribute_registration =
quote do
Module.register_attribute(__MODULE__, :fixtures, accumulate: true)
end
fixtures =
for fixture <- fixtures, is_atom(fixture), do: apply_fixture(fixture)
[attribute_registration | fixtures]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment