Created
June 30, 2012 20:37
-
-
Save nicholasjhenry/3025421 to your computer and use it in GitHub Desktop.
Inspired by "Making ActiveRecord Thin"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| customer = Shop::Directory.new(repository: User).find(1001) | |
| product = Shop::Warehouse.new(repository: Product).find(1002) | |
| transaction = Shop::Transaction.new(customer: customer, product: product, orders: Orders.new(repository: Order)) | |
| transaction.commit | |
| module Shop | |
| class Warehouse | |
| attr_reader :repository | |
| def initialize(args) | |
| @repository = args[:repository] | |
| end | |
| def find(id) | |
| Product.new repository.find_by_id(id) | |
| end | |
| end | |
| class Directory | |
| attr_reader :repository | |
| def initialize(args) | |
| @respository = args[:repository] | |
| end | |
| def find(id) | |
| Customer.new repository.find_by_id(id) | |
| end | |
| end | |
| class Orders | |
| attr_reader :repository | |
| def initialize(args) | |
| @repository = args[:repository] | |
| end | |
| def create(customer, product) | |
| Order.new repository.create(customer: customer.record, product: product.record) | |
| end | |
| end | |
| class Product | |
| attr_reader :record | |
| def initialize(args) | |
| @record = args[:record] | |
| end | |
| def sold! | |
| @record.update_attribute(:sold, true) | |
| end | |
| end | |
| class Customer | |
| attr_reader :record | |
| def initialize(args) | |
| @record = args[:record] | |
| end | |
| def pay(product) | |
| # perform the payment | |
| end | |
| end | |
| class Order | |
| attr_reader :record | |
| def initialize(args) | |
| @record = args[:record] | |
| end | |
| end | |
| class Transaction | |
| attr_reader :customer, :product, :orders, :status | |
| def initialize(args) | |
| @customer = args[:customer] | |
| @product = args[:product] | |
| @orders = args[:orders] | |
| end | |
| def commit | |
| @status = customer.pay(product) | |
| if success? | |
| commit! | |
| end | |
| end | |
| def commit! | |
| create_order | |
| if order.persisted? | |
| mark_product_as_sold | |
| end | |
| end | |
| def success? | |
| status === true | |
| end | |
| private | |
| def create_order | |
| @order = repository.create(customer, product) | |
| end | |
| def mark_product_as_sold | |
| @product.sold! | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment