Skip to content

Commit

Permalink
[#92] Add :default option to incr/3
Browse files Browse the repository at this point in the history
  • Loading branch information
cabol committed Dec 26, 2020
1 parent 13a9f59 commit 319fd6a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/nebulex/adapters/local.ex
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ defmodule Nebulex.Adapters.Local do
# Inherit default persistence implementation
use Nebulex.Adapter.Persistence

import Nebulex.Helpers
import Record

alias Nebulex.Adapters.Local.{Backend, Generation, Metadata}
Expand Down Expand Up @@ -485,13 +486,15 @@ defmodule Nebulex.Adapters.Local do
end

@impl true
def incr(%{meta_tab: meta_tab, backend: backend, stat_counter: ref}, key, incr, ttl, _opts) do
def incr(%{meta_tab: meta_tab, backend: backend, stat_counter: ref}, key, incr, ttl, opts) do
default = get_option(opts, :default, &is_integer/1, 0)

meta_tab
|> newer_gen()
|> backend.update_counter(
key,
{3, incr},
entry(key: key, value: 0, touched: Time.now(), ttl: ttl)
entry(key: key, value: default, touched: Time.now(), ttl: ttl)
)
|> update_stats(:write, ref)
end
Expand Down
7 changes: 7 additions & 0 deletions lib/nebulex/cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,10 @@ defmodule Nebulex.Cache do
(or expiry time) for the given key in **milliseconds**. Defaults
to `:infinity`.
* `:default` - If `key` is not present in Cache, the default value is
inserted as initial value of key before the it is incremented.
Defaults to `0`.
See the "Shared options" section at the module documentation for more options.
## Examples
Expand All @@ -835,6 +839,9 @@ defmodule Nebulex.Cache do
iex> MyCache.incr(:a, -1)
2
iex> MyCache.incr(:missing_key, 2, default: 10)
12
"""
@callback incr(key, incr :: integer, opts) :: integer

Expand Down
6 changes: 6 additions & 0 deletions test/shared/cache/entry_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,12 @@ defmodule Nebulex.Cache.EntryTest do
end
end

test "incr with default", %{cache: cache} do
assert cache.incr(:counter1, 1, default: 10) == 11
assert cache.incr(:counter2, 2, default: 10) == 12
assert cache.incr(:counter3, -2, default: 10) == 8
end

## Helpers

defp to_int(data) when is_integer(data), do: data
Expand Down

0 comments on commit 319fd6a

Please sign in to comment.