Created
May 12, 2014 13:27
-
-
Save mprymek/6e814d4a3c84ad3111c1 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
# | |
# library part | |
# | |
defprotocol PerxistentProto do | |
def refresh o | |
def save! o | |
end | |
defmodule Perxistent do | |
defmacro __using__(_) do | |
quote do | |
def save! o do | |
o |> Perxistent.Storage.put | |
o | |
end | |
def refresh o do | |
Perxistent.Storage.get __MODULE__, o.id | |
end | |
end | |
end | |
defmacro object type do | |
quote do | |
defimpl PerxistentProto, for: unquote(type) do | |
def refresh o do unquote(type).refresh o end | |
def save! o do unquote(type).save! o end | |
end | |
end | |
end | |
def refresh o do PerxistentProto.refresh o end | |
def save! o do PerxistentProto.save! o end | |
def load type, id do Perxistent.Storage.get type,id end | |
end | |
# | |
# client part - persistent object definition and storage implementation | |
# | |
require Perxistent | |
## implement persistent object | |
defmodule Person do | |
defstruct id: nil, name: "", surname: "" | |
use Perxistent | |
end | |
Perxistent.object Person | |
## implement storage | |
defmodule Perxistent.Storage do | |
def put o do | |
IO.puts "STORAGE: should store object #{inspect(o)}" | |
end | |
def get type, id do | |
IO.puts "STORAGE: should load object of type #{inspect(type)} and id #{inspect(id)}" | |
end | |
end | |
# | |
# client part - usage | |
# | |
# create object | |
o = %Person{id: :someid, name: "Miroslav", surname: "Prýmek"} | |
# save it | |
o = Perxistent.save! o | |
# modify it locally | |
o = o |> Map.put(:x,:x) | |
# refresh saved state | |
o = Perxistent.refresh o | |
# load object with id :someid from storage | |
o = Perxistent.load Person, :someid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment