Skip to content

Instantly share code, notes, and snippets.

@brycesenz
Created December 11, 2015 03:36
Show Gist options
  • Save brycesenz/aa6a25b5aea0b23b04f9 to your computer and use it in GitHub Desktop.
Save brycesenz/aa6a25b5aea0b23b04f9 to your computer and use it in GitHub Desktop.
class MarkReceiptPaid < ActiveInteraction::Base
# Required Params
#----------------------------------------------------------------------------
model :receipt
# Validations
#----------------------------------------------------------------------------
validates :receipt, :presence => true
# Execution
#----------------------------------------------------------------------------
def execute
if receipt.paid?
errors.add(:receipt, :already_paid)
else
create_reimbursement
mark_paid
receipt
end
end
# Private Methods
#----------------------------------------------------------------------------
private
def reimbursable_amount
receipt.amount
end
def mark_paid
receipt.paid_at = Time.zone.now
receipt.mark_paid
end
def create_reimbursement
receipt.build_reimbursement.tap do |r|
r.amount = reimbursable_amount
r.save!
end
end
end
class ReceiptsController < ApplicationController
# GET /customer/receipts
#-------------------------------------------------------------------
def index
render action: :index, locals: { receipts: Receipt.all }
end
# PUT /customer/receipts/1/mark_paid
#-------------------------------------------------------------------
def mark_paid
outcome = MarkReceiptPaid.run(receipt: unpaid_receipt)
if outcome.valid?
marked_paid
else
reimbursement_invalid
end
end
def marked_paid
flash[:alert] = "Marked as paid."
redirect_to action: :index
end
def reimbursement_invalid
flash[:alert] = "Error."
render action: :index
end
private
def unpaid_receipt
Receipt.unpaid.find(params[:id]) || (raise Exceptions::AccessDenied)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment