Skip to content

@dnagir /credit_card.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
CreditCard class
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.