Skip to content

Instantly share code, notes, and snippets.

@dougal
Created February 25, 2016 19:07
Show Gist options
  • Save dougal/f23d27ab31e1a901eac4 to your computer and use it in GitHub Desktop.
Save dougal/f23d27ab31e1a901eac4 to your computer and use it in GitHub Desktop.
class OrderCreator
def initialize(order_klass=Order, tax_calculator_klass=TaxCalculator)
end
def create(order_params)
order = order_klass.new(order_params)
tax_service = tax_calculator_klass.new
order = tax_service.calculate(order)
if order.save
[:succeeded, order]
else
[:failed, order]
end
end
end
class OrdersController
def create
service = OrderCreator.new
status, @order = service.create(params[:order])
if status == :succeeded
redirect_to @order
else
render action: 'new'
end
end
end
class TaxCalculator
TAX_RATE = 20.freeze # percent
def calculate(order)
order.tax = order.subtotal * (TAX_RATE / 100)
order.total = order.subtotal + order.tax
order
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment