Skip to content

Instantly share code, notes, and snippets.

@volgar1x
Created July 20, 2014 22:40
Show Gist options
  • Save volgar1x/6a1e08ab426bc45ab47b to your computer and use it in GitHub Desktop.
Save volgar1x/6a1e08ab426bc45ab47b to your computer and use it in GitHub Desktop.
defmodule AcmeApp.Flash do
import Plug.Conn
defmodule UnknownFlashException do
defexception key: nil
def message(exception), do: "unknown flash " <> inspect(exception.key)
end
defmodule Item do
defstruct value: nil, age: 0
def grow_old(%Item{ value: value, age: age }), do: %Item{ value: value, age: (age + 1) }
end
defp get_registry(conn), do: get_session(conn, :flash) || []
defp put_registry(reg, conn), do: put_session(conn, :flash, reg)
def get(conn, key) when is_atom(key) do
case get_registry(conn) do
[] -> { :error, { :unknown_key, key } }
reg -> { :ok, reg[key] }
end
end
def get!(conn, key) when is_atom(key) do
case get_registry(conn) do
[] -> raise UnknownFlashException, key: key
reg -> reg[key]
end
end
def put(conn, key, value) when is_atom(key) do
get_registry(conn)
|> Keyword.put(key, %Item{value: value})
|> put_registry(conn)
end
def clean(conn) do
get_registry(conn)
|> Enum.filter(fn %Item{age: age} -> age == 0 end)
|> Enum.map(&Item.grow_old/1)
|> put_registry(conn)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment