Skip to content

Instantly share code, notes, and snippets.

@r00k
Last active August 29, 2015 13:58
Show Gist options
  • Save r00k/10143752 to your computer and use it in GitHub Desktop.
Save r00k/10143752 to your computer and use it in GitHub Desktop.
Another DIP example
# Before:
class Product < ActiveRecord::Base
has_many :purchases
end
class Purchase < ActiveRecord::Base
belongs_to :product
# We don't want the receipt responsibilities in Purchase
def has_receipt?
receipt.present?
end
def receipt_id
receipt.id
end
def receipt_address
receipt.details.address
end
private
def receipt
Stripe::Receipt.find(stripe_order_id)
end
end
######################################################
# After:
class Product < ActiveRecord::Base
has_many :purchases
end
class Purchase < ActiveRecord::Base
belongs_to :product
end
class PurchaseWithReceipt < SimpleDelegator
def initialize(purchase, receipt_finder)
super(purchase)
@receipt_finder = receipt_finder
end
def has_receipt?
receipt.present?
end
def receipt_id
receipt.id
end
def receipt_address
receipt.details.address
end
private
def receipt
@receipt_finder.find(@purchase.stripe_order_id)
end
end
class ReceiptCollection
include Enumerable
def initialize(purchases, receipt_decorator_factory, receipt_finder)
@purchases = purchases
@receipt_decorator_factory = receipt_decorator_factory
@receipt_finder = receipt_finder
end
def each(&block)
receipts.each(&block)
end
private
def receipts
@purchases.map do |purchase|
@receipt_decorator_factory.new(purchase, receipt_finder)
end
end
end
# Use:
ReceiptCollection.new(product.purchases, PurchaseWithReceipt, Stripe::Receipt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment