Packages

An abstract cache store

Current section

Files

Jump to
simplecache lib simplecache.ex
Raw

lib/simplecache.ex

defmodule Simplecache do
@moduledoc """
An abstract cache store. There are multiple cache store implementations,
each having its own additional features.
Some implementations may not support all methods beyond the basic cache
methods of fetch, write, read, exist, and delete.
"""
@doc """
Fetches the value for the given key from the cache.
## Examples
iex> Simplecache.read("test")
nil
"""
def read(key) do
store().read(key)
end
@doc """
Writes the value to the cache, with the key.
Options are passed to the underlying cache implementation.
## Examples
iex> Simplecache.write("foo", "bar")
:ok
"""
def write(key, data, options \\ []) do
store().write(key, data, options)
end
@doc """
Fetches data from the cache, using the given key.
If there is data in the cache with the given key, then that data is returned.
Given function will be executed in the event of a cache miss.
The return value of the function will be written to the cache under the given cache key,
and that return value will be returned.
## Examples
iex> Simplecache.fetch("foo", fn -> "bar" end)
"bar"
iex> Simplecache.fetch("foo", fn -> "bar2" end)
"bar"
"""
def fetch(key, fun) do
case exist(key) do
true ->
read(key)
_ ->
data = fun.()
write(key, data)
data
end
end
@doc """
Returns true if the cache contains an entry for the given key.
Options are passed to the underlying cache implementation.
## Examples
iex> Simplecache.exist("not_there")
false
iex> Simplecache.write("there", "it is")
:ok
iex> Simplecache.exist("there")
true
"""
def exist(key, _options \\ []) do
read(key)
end
@doc """
Deletes an entry in the cache. Returns true if an entry is deleted.
Options are passed to the underlying cache implementation.
## Examples
iex> Simplecache.delete("foo")
true
"""
def delete(_key, _options \\ []), do: true
defp store do
case Application.get_env(:simplecache, :store) do
value when is_atom(value) -> Atom.to_string(value) |> store_name_to_module()
value when is_binary(value) -> store_name_to_module(value)
value -> value
end
end
defp store_name_to_module(name) do
String.to_existing_atom("#{__MODULE__}.Store#{String.capitalize(name)}")
end
end