public
Last active

CreditCard class

  • Download Gist
credit_card.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
class CreditCard
include ActiveAttr::Model
attribute :number
attribute :expiry
attribute :cvn
attribute :name
 
validate :must_be_valid
validates :number, :expiry, :cvn, :name, presence: true
 
def expiry_month
return nil unless expiry
expiry.match(/(\d+)/).try(:[], 1).try(:to_i)
end
def expiry_year
return nil unless expiry
year = expiry.match(/(\d+)(\s|\/|\\|-)+(\d{2,4})/)[3].to_i
year <= 99 ? 2000+year : year
end
 
def number_valid?
return false unless self.number
self.number =~ /^(\d|\s|-){5,25}$/
end
 
def expiry_valid?
return false unless self.expiry
return false unless (1..12).include? expiry_month
return false if expiry_year < 2012
true
end
 
def must_be_valid
errors.add(:number, 'should be a valid credit card number') unless number_valid?
errors.add(:expiry, 'should be a valid MM/YY') unless expiry_valid?
end
end
credit_card_spec.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
require 'faster_helper'
require 'active_attr'
require 'credit_card'
require 'shoulda-matchers'
 
describe CreditCard do
its(:number) { should be_nil }
its(:expiry) { should be_nil }
its(:cvn) { should be_nil }
its(:name) { should be_nil }
 
describe "#expiry_month" do
{
'12/1111' => 12,
'1/1111' => 1,
'1-1111' => 1,
'5/1111' => 5,
' 5 / 1111 ' => 5,
'' => nil,
' ' => nil,
nil => nil
}.each_pair do |expiry, month|
it "should be #{month} for #{expiry}" do
CreditCard.new(:expiry => expiry).expiry_month.should == month
end
end
end
 
describe "#expiry_year" do
{
'5/2012' => 2012,
'1-1111' => 1111,
'1/1111' => 1111,
'5/15' => 2015,
' 5 / 2012 ' => 2012,
nil => nil
}.each_pair do |expiry, year|
it "should be #{year} for #{expiry}" do
CreditCard.new(:expiry => expiry).expiry_year.should == year
end
end
end
it { should allow_value('4444333322221111').for :number }
it { should allow_value(' 4444333322221111 ').for :number }
it { should allow_value('4444-3333 2222 - 1111').for :number }
it { should_not allow_value('xxx').for :number }
it { should_not allow_value(' ').for :number }
it { should_not allow_value('4444333322221111'*20).for :number }
 
it { should allow_value('12/2012').for :expiry }
it { should allow_value('12-2012').for :expiry }
it { should allow_value('12 / 2012').for :expiry }
it { should_not allow_value('13/13').for :expiry }
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.