Last active
January 1, 2016 15:09
-
-
Save harlow/8162493 to your computer and use it in GitHub Desktop.
Example of using Casting Gem.
This file contains 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
class Purchase | |
include ActiveModel::Model | |
attr_accessor :customer # + other order related fields.. | |
# some validations | |
def save | |
if valid? | |
charge_customer && create_order | |
else | |
false | |
end | |
end | |
private | |
attr_reader :charge | |
def charge_customer | |
@charge = customer.create_charge(...) # the `create_charge` method is from `Customer` module | |
rescue ChargeFailedError => e | |
errors.add(...) | |
false | |
end | |
def create_order | |
customer.orders.create!(...) | |
end | |
end |
This file contains 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
require 'spec_helper' | |
describe Purchase, '#save' do | |
let(:customer) { double('Customer', create_charge: true) } | |
it 'charges the customer' do | |
Purchase.new(purchase_params).save | |
expect(customer).to have_received(:create_charge).with(...) | |
end | |
it 'perists the order' do | |
# ... | |
end | |
def purchase_params(options = {}) | |
{ | |
# ... | |
}.merge(options) | |
end | |
end |
This file contains 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
class PurchasesController < ApplicationController | |
def create | |
# service object: charges customer, persists the Order to DB | |
purchase = Purchase.new(purchase_params) | |
purchase.save | |
respond_with purchase | |
end | |
private | |
def purchase_params | |
params.require(:purchase).permit( | |
# product, price, etc | |
).merge( | |
customer: customer | |
) | |
end | |
def customer | |
current_user.cast_as(Customer) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment