Sha256: ad0bb2c34530c21bda7af4c2d425706b933ee97377ba8a2225bee019e4874473

Contents?: true

Size: 1.7 KB

Versions: 2

Compression:

Stored size: 1.7 KB

Contents

module ActsAsAccount
  class Journal < ActiveRecord::Base
    set_table_name :acts_as_account_journals
    
    has_many :postings
    has_many :accounts, :through => :postings
    
    class << self
      private :new
      private :create
      private :create!

      def current
        Thread.current[:acts_as_account_current] ||= create!
      end
      
      def clear_current
        Thread.current[:acts_as_account_current] = nil
      end
    end

    def transfer(amount, from_account, to_account, reference = nil, valuta = Time.now)
      transaction do
        logger.debug { "ActsAsAccount::Journal.transfer amount: #{amount} from:#{from_account.id} to:#{to_account.id} reference:#{reference.class.name}(#{reference.id}) valuta:#{valuta}" } if logger
        
        # to avoid possible deadlocks we need to ensure that the locking order is always
        # the same therfore the sort by id. 
        [from_account, to_account].sort_by(&:id).map(&:lock!)

        add_posting(amount * -1, from_account,   to_account, reference, valuta)
        add_posting(amount,        to_account, from_account, reference, valuta)
      end
    end
    
    private 
      def add_posting(amount, account, other_account, reference, valuta)
        posting = postings.build(
          :amount => amount, 
          :account => account, 
          :other_account => other_account,
          :reference => reference,
          :valuta => valuta)

        account.balance += posting.amount
        account.postings_count += 1
        account.last_valuta = account.last_valuta ? [account.last_valuta, posting.valuta].max : posting.valuta
      
        posting.save_without_validation
        account.save_without_validation
      end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
acts_as_account-1.1.1 lib/acts_as_account/journal.rb
acts_as_account-1.1.0 lib/acts_as_account/journal.rb