Created
February 25, 2016 19:07
-
-
Save dougal/f23d27ab31e1a901eac4 to your computer and use it in GitHub Desktop.
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 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 |
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 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 |
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 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