Skip to content

Instantly share code, notes, and snippets.

@cpjk
Created August 4, 2015 06:55
Show Gist options
  • Save cpjk/9a0aa3127c13d783c4c0 to your computer and use it in GitHub Desktop.
Save cpjk/9a0aa3127c13d783c4c0 to your computer and use it in GitHub Desktop.
defmodule Canary.Abilities do
defmacro can(user, actions, targets, when: condition) do # This macro throws an error when used
quote do
defimpl Canada.Can, for: unquote(user).__struct__ do
def can?(unquote(user), unquote(actions), unquote(targets)) when unquote(condition), do: true
end
end
end
defmacro can2(user, actions, targets, when: condition) do # This macro works
quote do
def can?(unquote(user), unquote(actions), unquote(targets)) when unquote(condition), do: true
end
end
end
@cpjk
Copy link
Author

cpjk commented Aug 4, 2015

iex(112)> defmodule A do; Canary.Abilities.can %User{id: id}, :index, %User{}, when: id in [1,2]; end
iex:112: warning: redefining module A
** (CompileError) iex:112: undefined function id/0
(elixir) expanding macro: Kernel.defimpl/3
iex:112: A (module)
(canary) expanding macro: Canary.Abilities.can/4
iex:112: A (module)

iex(112)> defmodule A do; Canary.Abilities.can2 %User{id: id}, :index, %User{}, when: id in [1,2]; end
iex:112: warning: redefining module A
{:module, A,
<<70, 79, 82, 49, 0, 0, 5, 40, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 150, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 2, 104, 2, ...>>,
{:can?, 3}}

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