-
-
Save wallace/3284741 to your computer and use it in GitHub Desktop.
| class Order < ActiveRecord::Base | |
| has_many :line_items | |
| validates :total_price, numericality: true | |
| before_create :apply_returning_customer_discount, if: lambda { |order| order.returning_customer? } | |
| def apply_returning_customer_discount | |
| self.total_price = self.total_price * 0.9 | |
| end | |
| end |
Oh my... not only is the grammar horrible, but I mixed several different drafts, and some crass language. Please, allow me to try again:
Why use callbacks at all? Rails' notion of callbacks are a hack which allow you to be lazy and not think about the domain; instead delve more deeply into the problem space and work to uncover a better abstraction. In domain language - what the heck is an Order? To me, an Order is probably an artifact that only exists after one has finished a purchase. After you've "checked out."
Maybe a better abstraction is a Cart which contains a collection of Items, or SKUs a customer intends to purchase? A Cart could delegate to a PriceRegister or some form of calculator to sum totals, and then after checkout an Order, or perhaps Receipt, or maybe BillOfSale could be stored for later use.
s/crass/snarky/
Why use callbacks at all? Rails notion of callbacks are a hack to let you be lazy and not use your brain; instead delve more deeply into the problem space and work to uncover a better abstraction. For example, from pure domain terms - what the heck is an order? And order is an artifact that only really exists after one has checked out.
For example, maybe a better abstraction is a
Cartwhich contains a collection of things a customer intends to purchase? ACartcould delegate to aPriceRegisteror some form of calculator to sum totals, and then after checkout anOrder, or perhapsReceipt, or maybeBillOfSalecould be stored for later use.