Skip to content

Instantly share code, notes, and snippets.

@ntrepid8
Created November 2, 2016 16:06
Show Gist options
  • Save ntrepid8/975cd809ebcc8ba36a556dd862ce36d8 to your computer and use it in GitHub Desktop.
Save ntrepid8/975cd809ebcc8ba36a556dd862ce36d8 to your computer and use it in GitHub Desktop.
Elixir GenServer Template
defmodule GenServerTpl do
@moduledoc """
A GenServer template for a "singleton" process.
"""
use GenServer
# Initialization
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts, [name: __MODULE__])
end
def init(opts) do
Process.send_after(self(), {:baz, ["spam&eggs"]}, 3_000)
state = %{
foo: nil,
bar: nil,
baz: nil
}
{:ok, state}
end
# API
def foo(value) do
GenServer.call(__MODULE__, {:foo, [value]})
end
def bar(value) do
GenServer.cast(__MODULE__, {:bar, [value]})
end
# Callbacks
def handle_call({:foo, [value]}, _from, state) do
resp = "value: #{inspect value}"
state = %{state|foo: value}
{:reply, resp, state}
end
def handle_cast({:bar, [value]}, state) do
updated_value = transform_bar(value)
state = %{state|bar: updated_value}
{:noreply, state}
end
def handle_info({:baz, [value]}, state) do
state = %{state|baz: value}
{:noreply, state}
end
# Helpers
defp transform_bar(value) do
"transformed: #{inspect value}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment