Created
July 1, 2018 15:35
-
-
Save ejpcmac/3aad916282ffd98a55ba5d77a2f6fc3e to your computer and use it in GitHub Desktop.
Recursively defining fixtures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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