Skip to content

Instantly share code, notes, and snippets.

@harlow
Last active January 1, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harlow/8162493 to your computer and use it in GitHub Desktop.
Save harlow/8162493 to your computer and use it in GitHub Desktop.
Example of using Casting Gem.
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
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
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