Class: Ask::TokenUsage::Stores::Memory
- Defined in:
- lib/ask/token_usage/stores/memory.rb
Overview
In-memory store: per-process state keyed by owner, guarded by one reentrant monitor. Perfect for scripts, tests, and demos. Every wallet built without a configured store shares this class's process state via the default Configuration store.
Instance Method Summary collapse
- #append(owner, entry) ⇒ Object
- #balance(owner) ⇒ Object
- #entries(owner, kind: nil, since: nil) ⇒ Object
-
#initialize ⇒ Memory
constructor
A new instance of Memory.
- #with_lock(owner) ⇒ Object
- #write_balance(owner, balance) ⇒ Object
Constructor Details
#initialize ⇒ Memory
Returns a new instance of Memory.
14 15 16 17 18 19 |
# File 'lib/ask/token_usage/stores/memory.rb', line 14 def initialize @monitor = Monitor.new @balances = Hash.new(0) @ledgers = Hash.new { |hash, key| hash[key] = [] } @next_id = 0 end |
Instance Method Details
#append(owner, entry) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/ask/token_usage/stores/memory.rb', line 36 def append(owner, entry) with_lock(owner) do @next_id += 1 persisted = entry.with(id: @next_id) @ledgers[owner] << persisted persisted end end |
#balance(owner) ⇒ Object
21 22 23 |
# File 'lib/ask/token_usage/stores/memory.rb', line 21 def balance(owner) @balances[owner] end |
#entries(owner, kind: nil, since: nil) ⇒ Object
25 26 27 28 29 30 |
# File 'lib/ask/token_usage/stores/memory.rb', line 25 def entries(owner, kind: nil, since: nil) result = @ledgers[owner] result = result.select { |entry| entry.kind == kind } if kind result = result.select { |entry| entry.created_at >= since } if since result end |
#with_lock(owner) ⇒ Object
32 33 34 |
# File 'lib/ask/token_usage/stores/memory.rb', line 32 def with_lock(owner) @monitor.synchronize { yield } end |
#write_balance(owner, balance) ⇒ Object
45 46 47 48 49 |
# File 'lib/ask/token_usage/stores/memory.rb', line 45 def write_balance(owner, balance) with_lock(owner) do @balances[owner] = balance end end |