Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple written "Model Concern" for adding active merchant
# 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
You can’t perform that action at this time.