Created
July 15, 2015 14:21
-
-
Save anonymous/3aec079cc0de5171e5cf to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Datastore do | |
use Behaviour | |
@type key :: any | |
@type value :: any | |
defcallback start_link() :: Agent.t | |
defcallback get(Agent.t, key) :: value | |
defcallback put(Agent.t, key, value) :: :ok | |
defmacro __using__(_) do | |
quote do | |
@behaviour Datastore | |
def start_link() do | |
Agent.start_link(fn -> %{ } end, name: __MODULE__) | |
end | |
def get(datastore, key) do | |
Agent.get(datastore, &Map.get(&1, key)) | |
end | |
def put(datastore, key, value) do | |
Agent.update(datastore, &Map.put(&1, key, value)) | |
end | |
defoverridable start_link: 0, get: 2, put: 3 | |
end | |
end | |
def put(datastore, key, val) do | |
__MODULE__.put(datastore, key, val) # How do I get the name/module ? | |
end | |
end | |
defmodule Driver do | |
use Datastore | |
def start_link() do | |
Agent.start_link(fn -> HashDict.new end) # Could use __MODULE__ as the name? | |
end | |
def get(datastore, key) do | |
Agent.get(datastore, &HashDict.get(&1, key)) | |
end | |
def put(datastore, key, value) do | |
IO.puts "Rumpen stumpen" | |
Agent.update(datastore, fn dict -> HashDict.put(dict, key, value) end) | |
end | |
end | |
{:ok, mem} = Driver.start_link() | |
Datastore.put(mem, "hello", "world") # fail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment