Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active August 20, 2020 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/2aa1bde5d6cddeec6e0d1421923e6e35 to your computer and use it in GitHub Desktop.
Save inopinatus/2aa1bde5d6cddeec6e0d1421923e6e35 to your computer and use it in GitHub Desktop.
Adderall
# app/lib/adderall.rb
module Adderall
def adderall(column_name, relation = self, filter = :itself)
owner = proxy_association.owner
records = proxy_association.target
if loaded? || owner.new_record?
relation = none
else
records = records.select(&:new_record?)
end
relation.sum(column_name) + records.select(&filter).sum(&column_name)
end
end
# Example usage:
# app/models/record/invoice.rb
class Record::Invoice < ApplicationRecord
before_validation do
self.sub_total = receivables.computed_line_price_sum
end
has_many :receivables, autosave: true do
include Adderall
def computed_line_price_sum
adderall(:line_price, not_freight, :not_freight?)
end
end
#...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment