Class: Ask::Tokens::Rails::ActiveRecordStore

Inherits:
Stores::Store
  • Object
show all
Defined in:
lib/ask/tokens/rails/stores/active_record_store.rb

Overview

ActiveRecord-backed wallet store. Each mutation (grant/deduct) does its own read-write under a single DB call. The wallet row is created lazily on first access. No outer transaction wrapping — each AR create/update handles its own atomicity.

Instance Method Summary collapse

Instance Method Details

#append(owner, entry) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ask/tokens/rails/stores/active_record_store.rb', line 34

def append(owner, entry)
  row = find_or_create_wallet!(owner)
  meta = entry. || {}
  txn = Ask::Tokens::TokenTransaction.create!(
    token_wallet_id: row.id,
    entry_type: entry.kind.to_s,
    amount: entry.amount,
    reason: entry.reason,
    metadata: meta,
    expires_at: entry.expires_at,
    balance: entry.balance,
    created_at: entry.created_at,
    **(meta)
  )
  entry.with(id: txn.id)
end

#balance(owner) ⇒ Object



13
14
15
# File 'lib/ask/tokens/rails/stores/active_record_store.rb', line 13

def balance(owner)
  resolve_wallet(owner)&.balance || 0
end

#entries(owner, kind: nil, since: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/ask/tokens/rails/stores/active_record_store.rb', line 17

def entries(owner, kind: nil, since: nil)
  row = resolve_wallet(owner)
  return [] unless row

  scope = row.token_transactions.order(:created_at)
  scope = scope.where(entry_type: kind.to_s) if kind
  scope = scope.where("created_at >= ?", since) if since
  scope.map { |t| to_entry(t) }
end

#with_lock(owner) ⇒ Object

No-op for in-process locking. For production with PostgreSQL, this could use row-level locks. SQLite uses file-level locks which are handled by the OS.



30
31
32
# File 'lib/ask/tokens/rails/stores/active_record_store.rb', line 30

def with_lock(owner)
  yield
end

#write_balance(owner, amount) ⇒ Object



51
52
53
54
# File 'lib/ask/tokens/rails/stores/active_record_store.rb', line 51

def write_balance(owner, amount)
  row = find_or_create_wallet!(owner)
  row.update_column(:balance, amount)
end