Created
July 24, 2013 04:26
-
-
Save elgalu/6068066 to your computer and use it in GitHub Desktop.
Services Objects: Moving Behavior from Controllers http://goo.gl/jtjDw
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
| module OrderService | |
| def self.create(listener, user, order_attrs) | |
| Order.new(order_attrs.merge(user: current_user)) | |
| if order.save | |
| transaction = PaymentProcessor.create_payment(order) | |
| listener.order_creation_succeeded(order, transaction) | |
| else | |
| listener.order_creation_failed(order) | |
| end | |
| end | |
| end |
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
| class OrdersController < ApplicationController | |
| respond_to :html, :json | |
| def create | |
| order_attrs = sanitize_attributes(params[:order]) | |
| OrderService.create(self, current_user, order_attrs) | |
| end | |
| def order_creation_succeeded(order, transaction) | |
| flash[:notice] = "Transaction Id: #{transaction}" | |
| respond_with(order) do |format| | |
| format.html { redirect_to order_path(order) } | |
| format.json { render status: 200, json: order, serializer: OrderSerializer } | |
| end | |
| end | |
| def order_creation_failed(order) | |
| @order = order | |
| respond_with(@order) do |format| | |
| format.html { render 'new' } | |
| format.json { render status: 422, json: order, serializer: OrderSerializer } | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment