Skip to content

Instantly share code, notes, and snippets.

@jasondew
Created June 24, 2010 00:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasondew/450783 to your computer and use it in GitHub Desktop.
Save jasondew/450783 to your computer and use it in GitHub Desktop.
class CreditCard < ActiveRecord::Base
belongs_to :order
has_one :billing_address, :as => :addressable, :class_name => "Address", :dependent => :destroy
accepts_nested_attributes_for :billing_address
before_validation :clean_number
validates_presence_of :first_name, :last_name, :number, :expiration_month, :expiration_year
validates_inclusion_of :expiration_month, :in => (1..12), :message => "should be between 1 and 12"
validates_inclusion_of :expiration_year, :in => (Date.today.year..(Date.today.year+10)),
:message => "should be between #{Date.today.year} and #{Date.today.year + 10}"
validates_associated :billing_address
def name
"#{first_name} #{last_name}"
end
def details
"#{censored_number} expires #{expiration_month}/#{expiration_year}"
end
def censored_number
"X" * (number.length - 4) + number[(number.length - 4)..number.length]
end
def authorize!
card = ActiveMerchant::Billing::CreditCard.new(:number => number, :month => expiration_month,
:year => expiration_year, :first_name => first_name,
:last_name => last_name)
address = billing_address.for_active_merchant.merge(:name => "#{first_name} #{last_name}")
response = Paypal.gateway.authorize(order.total * 100, card, :ip => ip_address, :billing_address => address)
if (status = response.success?)
update_attributes :authorization => response.authorization
order.update_attributes :state => "authorized"
else
update_attributes :error => response.message
order.update_attributes :state => "authorization_failed"
end
status
end
private
def clean_number
self.number.gsub! /[^0-9]/, ""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment