Class: QueryGuard::Store
- Inherits:
-
Object
- Object
- QueryGuard::Store
- Defined in:
- lib/query_guard/store.rb
Overview
Minimal store abstraction for rate counters. Default: in-process MemoryStore. In production you can swap with Redis-based adapter.
Instance Method Summary collapse
-
#add_to_set(key, member, ttl: 60) ⇒ Object
"Set" emulation: store a Hash of members => true with ttl.
-
#incr(key, ttl: 60, by: 1) ⇒ Object
Increment integer key, expiring after ttl seconds.
-
#initialize(cache: nil) ⇒ Store
constructor
A new instance of Store.
- #read(key) ⇒ Object
- #set_size(key) ⇒ Object
Constructor Details
#initialize(cache: nil) ⇒ Store
Returns a new instance of Store.
9 10 11 |
# File 'lib/query_guard/store.rb', line 9 def initialize(cache: nil) @cache = cache || ActiveSupport::Cache::MemoryStore.new(size: 8.megabytes) end |
Instance Method Details
#add_to_set(key, member, ttl: 60) ⇒ Object
"Set" emulation: store a Hash of members => true with ttl
25 26 27 28 29 30 31 |
# File 'lib/query_guard/store.rb', line 25 def add_to_set(key, member, ttl: 60) h = @cache.read(key) h = {} unless h.is_a?(Hash) h[member] = true @cache.write(key, h, expires_in: ttl) h.size end |
#incr(key, ttl: 60, by: 1) ⇒ Object
Increment integer key, expiring after ttl seconds
14 15 16 17 18 |
# File 'lib/query_guard/store.rb', line 14 def incr(key, ttl: 60, by: 1) val = (@cache.read(key) || 0).to_i + by @cache.write(key, val, expires_in: ttl) val end |
#read(key) ⇒ Object
20 21 22 |
# File 'lib/query_guard/store.rb', line 20 def read(key) @cache.read(key) end |
#set_size(key) ⇒ Object
33 34 35 36 |
# File 'lib/query_guard/store.rb', line 33 def set_size(key) h = @cache.read(key) h.is_a?(Hash) ? h.size : 0 end |