Skip to content

Instantly share code, notes, and snippets.

@asonge
Forked from anonymous/behaviour.ex
Last active August 29, 2015 14:25
Show Gist options
  • Save asonge/e2999670760d406711d3 to your computer and use it in GitHub Desktop.
Save asonge/e2999670760d406711d3 to your computer and use it in GitHub Desktop.
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