Created
December 18, 2013 22:34
-
-
Save srt32/8031051 to your computer and use it in GitHub Desktop.
fourthmeal#transactions_controller refactor process Blog post about it: http://www.simontaranto.com/2013/12/11/it-all-comes-together-ruby-js-and-functional-programming.html
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
Before: | |
def create | |
@transaction = current_order.build_transaction(transaction_params) | |
@transaction.update(:order_id => current_order.id) | |
if @transaction.save | |
@transaction.pay! | |
if current_user | |
current_order.update(:user_id => current_user.id, :status => "paid") | |
else | |
current_order.update(:status => "paid") | |
end | |
session[:current_order] = nil | |
OrderMailer.order_confirmation(@transaction).deliver | |
flash[:notice] = "Successfully created your order!" | |
redirect_to transaction_path(@transaction) | |
else | |
flash[:notice] = "There was a problem creating your order!" | |
render :new | |
end | |
end | |
The end: | |
#app/controllers/transactions_controller.rb | |
def create | |
CompletePurchase.new(current_user, current_order, current_restaurant).create(updated_params, | |
->(restaurant, transaction) { | |
session[:current_order] = nil | |
flash[:notice] = "Successfully created your order!" | |
redirect_to restaurant_transaction_path(restaurant, transaction) | |
}, | |
-> { | |
flash[:notice] = "There was a problem creating your order!" | |
render :new | |
}) | |
end | |
#app/use_cases/complete_purchase.rb | |
class CompletePurchase | |
def initialize(user, order, restaurant, mailer=OrderMailer) | |
@user = user | |
@order = order | |
@restaurant = restaurant | |
@mailer = mailer | |
end | |
def create(params, success, failure) | |
ActiveRecord::Base.transaction do | |
transaction = Transaction.new(params) | |
if transaction.save | |
transaction_successfully_saved(transaction) | |
success.call(@restaurant, transaction) | |
else | |
failure.call | |
end | |
end | |
end | |
def transaction_successfully_saved(trans) | |
@order.update(:user_id => @user.id) if @user | |
@mailer.order_confirmation(trans).deliver | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment