Skip to content

Commit

Permalink
Merge pull request #3 from renderedtext/vm/fetch_passes_key_to_fallback
Browse files Browse the repository at this point in the history
Pass key to fallback function
  • Loading branch information
VeljkoMaksimovic authored Oct 11, 2022
2 parents 7bd0d36 + 6c0737e commit 711b10e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/cacheman.ex
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ defmodule Cacheman do
def fetch(name, key, put_opts, fallback) do
case get(name, key) do
{:ok, nil} ->
case fallback.() do
case if is_function(fallback, 0), do: fallback.(), else: fallback.(key) do
{:ok, value} ->
put(name, key, value, put_opts)
{:ok, value}
Expand Down
10 changes: 8 additions & 2 deletions test/cacheman_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,17 @@ defmodule CachemanTest do
key = "test-#{:rand.uniform(10_000)}"

assert {:ok, nil} = Cacheman.get(:broken, key)
assert {:ok, "hello"} = Cacheman.fetch(:broken, key, fn -> {:ok, "hello"} end)

assert {:ok, "hello"} =
Cacheman.fetch(:broken, key, fn passed_key ->
assert passed_key == key
{:ok, "hello"}
end)

assert {:ok, nil} = Cacheman.get(:broken, key)

assert {:ok, "this-is-not-used"} =
Cacheman.fetch(:broken, key, fn -> {:ok, "this-is-not-used"} end)
Cacheman.fetch(:broken, key, fn _ -> {:ok, "this-is-not-used"} end)
end

test "TTL for keys" do
Expand Down

0 comments on commit 711b10e

Please sign in to comment.