Created
January 14, 2016 21:41
-
-
Save almightycouch/43375ba6bbe995f041a0 to your computer and use it in GitHub Desktop.
Elixir Bucket module implementing the Access behaviour
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 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