Skip to content

Instantly share code, notes, and snippets.

@almightycouch
Created January 14, 2016 21:41
Show Gist options
  • Save almightycouch/43375ba6bbe995f041a0 to your computer and use it in GitHub Desktop.
Save almightycouch/43375ba6bbe995f041a0 to your computer and use it in GitHub Desktop.
Elixir Bucket module implementing the Access behaviour
defmodule Bucket do
@behaviour Access
defstruct pid: nil
def start_link(default \\ %{}) when is_map(default) do
case Agent.start_link(fn -> default end) do
{:ok, pid} ->%__MODULE__{pid: pid}
{:error, message} -> raise message
end
end
def fetch(%__MODULE__{pid: pid}, key) do
{:ok, Agent.get(pid, &(&1))[key]}
end
def get_and_update(%__MODULE__{pid: pid} = handle, key, fun) do
{Agent.get_and_update(pid, fn state ->
{_, new_val} = fun.(key)
{new_val, Map.put(state, key, new_val)}
end), handle}
end
defimpl Inspect do
def inspect(bucket, _) do
Kernel.inspect(bucket.pid)
|> String.replace("PID", "Bucket")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment