Class: ActsAsAccount::Account

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/acts_as_account/account.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create(attributes = nil) ⇒ Object



36
37
38
39
40
# File 'lib/acts_as_account/account.rb', line 36

def create(attributes = nil)
  find_on_error(attributes) do
    super
  end
end

.create!(attributes = nil) ⇒ Object



30
31
32
33
34
# File 'lib/acts_as_account/account.rb', line 30

def create!(attributes = nil)
  find_on_error(attributes) do
    super
  end
end

.delete_account(number) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/acts_as_account/account.rb', line 42

def (number)
  transaction do
     = find(number)
    raise ActiveRecord::ActiveRecordError, "Cannot be deleted" unless .deleteable?

    .holder.destroy if [ManuallyCreatedAccount, GlobalAccount].include?(.holder.class)
    .destroy
  end
end

.find_on_error(attributes) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/acts_as_account/account.rb', line 52

def find_on_error(attributes)
  yield

# Trying to create a duplicate key on a unique index raises StatementInvalid
rescue ActiveRecord::StatementInvalid
  record = if attributes[:holder]
    attributes[:holder].(attributes[:name])
  else
    where(
      :holder_type => attributes[:holder_type],
      :holder_id   => attributes[:holder_id],
      :name        => attributes[:name]
    ).first
  end
  record || raise("Cannot find or create account with attributes #{attributes.inspect}")
end

.for(name) ⇒ Object



26
27
28
# File 'lib/acts_as_account/account.rb', line 26

def for(name)
  GlobalAccount.find_or_create_by(name: name).
end

.recalculate_all_balancesObject



16
17
18
19
20
21
22
23
24
# File 'lib/acts_as_account/account.rb', line 16

def recalculate_all_balances
  find_each do ||
    .update_columns(
      balance:        .postings.sum(:amount),
      postings_count: .postings.count,
      last_valuta:    .postings.maximum(:valuta)
    )
  end
end

Instance Method Details

#deleteable?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/acts_as_account/account.rb', line 70

def deleteable?
  postings.empty? && journals.empty?
end