Skip to content

Instantly share code, notes, and snippets.

@joegaudet
Last active November 28, 2019 20:27
Show Gist options
  • Save joegaudet/e68ff68481ae3cabeb00944c4e8ec895 to your computer and use it in GitHub Desktop.
Save joegaudet/e68ff68481ae3cabeb00944c4e8ec895 to your computer and use it in GitHub Desktop.
class Accounting::LedgerItem < ApplicationRecord
acts_as_ledger_item
belongs_to :recipient, polymorphic: true
belongs_to :sender, polymorphic: true
has_many :line_items
# # specific line items
attribute :status, :string, default: 'open'
attribute :issue_date, :date, default: Date.current
attribute :period_start, :date, default: Date.current
def ordered_items
TypedCollectionProxy.new(self, :line_items, Accounting::LineItems::OrderedItem)
end
def discounts
TypedCollectionProxy.new(self, :line_items, Accounting::LineItems::Discount)
end
def fees
TypedCollectionProxy.new(self, :line_items, Accounting::LineItems::Fee)
end
def payments
TypedCollectionProxy.new(self, :line_items, Accounting::LineItems::Payment)
end
class TypedCollectionProxy
delegate *Array.public_instance_methods, to: :array
def initialize(base, attribute, type)
@base = base
@attribute = attribute
@type = type
end
def build(attribute = {})
@base.send(@attribute) << @type.new(attribute)
end
def array
@base.send(@attribute).select { |li| li.type.safe_constantize == @type }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment