rails/activerecord/test/models/invoice.rb
Alberto Mota afa83350de Deprecates Enumerable#sum and Array#sum
Ruby (2.4+) includes a native implementation of `sum` with significant
performance gains. Rails 7.1 will be removing `Enumerable#sum` and
`Array#sum` in favor of Ruby's native implementation.

This commit adds a deprecation warning to calls with non-numeric
arguments without a suitable initial argument as those will be required
once Rails removes this functionality.

Some examples that will now trigger a deprecation warning:
    >> %w[foo bar].sum
    >> [[1, 2], [3, 4, 5]].sum

To avoid the deprecation warning they should now invoked as follows:
    >> %w[foo bar].sum('')
    >> [[1, 2], [3, 4, 5]].sum([])

In order to prepare for the deprecation on Rails 7.1, it also
deprecates `[nil].sum == 0`, which in Ruby's native implementation
throws a `TypeError`.
2021-05-03 10:26:39 -07:00

8 lines
271 B
Ruby

# frozen_string_literal: true
class Invoice < ActiveRecord::Base
has_many :line_items, autosave: true
has_many :shipping_lines, -> { from("shipping_lines") }, autosave: true
before_save { |record| record.balance = record.line_items.map(&:amount).compact.sum }
end