Class: SimpleWallet::TransferService

Inherits:
Service
  • Object
show all
Defined in:
app/services/simple_wallet/transfer_service.rb

Instance Method Summary collapse

Methods inherited from Service

#errors_sentence, #t

Constructor Details

#initialize(from:, to:, amount:, note:) ⇒ TransferService

Returns a new instance of TransferService.



7
8
9
10
11
12
# File 'app/services/simple_wallet/transfer_service.rb', line 7

def initialize(from:, to:, amount:, note:)
  @from = from
  @to = to
  @amount = amount
  @note = note
end

Instance Method Details

#transfer(set_transaction_isolation_level: true) ⇒ Object

Use set_transaction_isolation_level: false to avoid getting this exception:

ActiveRecord::TransactionIsolationError (cannot set isolation when joining a transaction)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/services/simple_wallet/transfer_service.rb', line 16

def transfer(set_transaction_isolation_level: true)
  # Checking account's balance should be wrapped in a transaction:
  # Setting transaction isolation level in tests is problematic due to nested transactions :|
  isolation_level = (Rails.env.test? || !set_transaction_isolation_level) ? nil : :serializable

  success = ActiveRecord::Base.transaction(isolation: isolation_level) do
    return false unless valid?

    unless debiting_service.debit(set_transaction_isolation_level: false)
      copy_errors_from(debiting_service)
      return false
    end

    unless crediting_service.credit(set_transaction_isolation_level: false)
      copy_errors_from(crediting_service)
      raise ActiveRecord::Rollback
    end

    after_operation
    true
  end

  !!success
end