Forked from jordelver/booking_payment_controller.rb
Last active
December 15, 2015 17:09
-
-
Save harlow/5294577 to your computer and use it in GitHub Desktop.
Use ActiveModel::Model for validations on non-AR objects
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 BookingPaymentsController < ApplicationController | |
def create | |
booking_payment = BookingPayment.new(booking_payment_params) | |
booking_payment.pay | |
respond_with payment, location: balance_trip_path | |
end | |
private | |
def booking_payment_params | |
params.require(:booking_payment).permit( | |
:card_number, | |
:card_expiry | |
).merge( | |
ip_address: request.ip, | |
booking: booking | |
) | |
end | |
def booking | |
# ... | |
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 BookingPayment | |
include ActiveModel::Model | |
attr_accessor :booking, :card_number, :card_expiry | |
validates :booking, presence: true | |
validates :card_number, presence: true, credit_card_number: true | |
validates :card_expiry, presence: true | |
def pay | |
if valid? && payment_processed? | |
create_transaction | |
create_payment | |
end | |
end | |
private | |
def payment_processed? | |
process_payment_response.success? | |
end | |
def process_payment_response | |
@process_payment_response ||= process_payment.response | |
end | |
def process_payment | |
PaymentProcessor.process(booking, card_number: card_number, card_expiry: card_expiry) | |
end | |
def create_transaction | |
Transaction.record_purchase(booking, process_payment_response) | |
end | |
def create_payment | |
# ... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment