Skip to content

Instantly share code, notes, and snippets.

@arjan
Created February 16, 2016 15:53
Show Gist options
  • Save arjan/16ed99f656eef9b8fd58 to your computer and use it in GitHub Desktop.
Save arjan/16ed99f656eef9b8fd58 to your computer and use it in GitHub Desktop.
GenServer macros
defmodule GenServer.Interface do
defmacro defcall(function, arity) do
args = for n <- :lists.seq(1,arity), do: {"arg" <> Integer.to_string(n) |> String.to_atom, [], Elixir}
quote do
def unquote(function)(server, unquote_splicing(args)) do
GenServer.call(server, {unquote(function), unquote_splicing(args)})
end
end
end
defmacro defcast(function, arity) do
args = for n <- :lists.seq(1,arity), do: {"arg" <> Integer.to_string(n) |> String.to_atom, [], Elixir}
quote do
def unquote(function)(server, unquote_splicing(args)) do
GenServer.cast(server, {unquote(function), unquote_splicing(args)})
end
end
end
end
@arjan
Copy link
Author

arjan commented Feb 16, 2016

Usage:

defmodule StateServer do
  use GenServer
  import GenServer.Interface

  defcall get_state, 0
  defcall set_state, 1

  ...
end

generates:

def get_state(server) do
    GenServer.call(server, {:get_state})
end

def set_state(server, arg1) do
    GenServer.call(server, {:get_state, arg1})
end

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