Created
October 9, 2013 07:15
-
-
Save we4tech/6897410 to your computer and use it in GitHub Desktop.
Simple written "Model Concern" for adding active merchant
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
# Integrate with ActiveMerchant and Expose active merchant related methods. | |
# | |
# This module also includes Validator for ActiveMerchant. | |
module Concerns::AsActiveMerchant | |
extend ActiveSupport::Concern | |
included do | |
validates_with Validators::ActiveMerchant, if: :cc_number_is_changed? | |
end | |
def cc_number_is_changed? | |
new_record? || changed_attributes['number'].present? | |
end | |
# Create ActiveMerchant::Billing::CreditCard object instance from the instance | |
# data. | |
# | |
# Returns ActiveMerchant::Billing::CreditCard instance | |
def as_active_merchant | |
attrs = { brand: self.brand, | |
first_name: self.first_name, | |
last_name: self.last_name, | |
number: self.number, | |
month: self.month, | |
year: self.year } | |
if self.verification_value.present? | |
attrs[:verification_value] = self.verification_value | |
end | |
ActiveMerchant::Billing::CreditCard.new attrs | |
end | |
def display_number | |
as_active_merchant.display_number | |
end | |
module ClassMethods | |
# Return list of credit card brand names | |
def brands | |
ActiveMerchant::Billing::CreditCard.card_companies.keys | |
end | |
end | |
module Validators | |
class ActiveMerchant < ActiveModel::Validator | |
def validate(record) | |
am_cc = record.as_active_merchant | |
unless am_cc.valid? | |
record.errors[:base] << 'Invalid Credit Card Information' | |
am_cc.errors.each do |k, v| | |
record.errors[k] = v.join(', ') | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment