Created
March 20, 2025 21:28
-
-
Save profh/807f29d72e2ec7a07b7d48eff3f82a17 to your computer and use it in GitHub Desktop.
Credit Card Model
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
# where we do the main work of creating a credit card... | |
class CreditCard | |
VALID_TYPES = [ | |
CreditCardType.new("AMEX", /^3(4|7)\d{13}$/), | |
CreditCardType.new("DCCB", /^30[0-5]\d{11}$/), | |
CreditCardType.new("DISC", /^6(011|5\d\d)\d{12}$/), | |
CreditCardType.new("MC", /^5[1-5]\d{14}$/), | |
CreditCardType.new("VISA", /^4\d{12}(\d{3})?$/) | |
] | |
attr_reader :number, :type | |
attr_reader :expiration_year, :expiration_month | |
def initialize(number, expiration_year, expiration_month) | |
@expiration_year, @expiration_month = expiration_year, expiration_month | |
# set number to a string so we can use regex | |
@number = number.to_s | |
# .detect (part of Enumerable) passes each entry in enum to block and returns the first for which block is not false. | |
# If no object matches, it will return nil | |
@type = VALID_TYPES.detect { |type| type.match(@number) } | |
end | |
def expired? | |
today = Date.today | |
expiration_year < today.year or (expiration_year == today.year and expiration_month < today.month) | |
end | |
def valid? | |
!expired? and !type.nil? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment