Skip to content

Instantly share code, notes, and snippets.

@liquidz
Created September 24, 2008 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liquidz/12505 to your computer and use it in GitHub Desktop.
Save liquidz/12505 to your computer and use it in GitHub Desktop.
ruby class for ISBN
class ISBN
attr_reader :isbn
# =initialize
def initialize(isbn)
@isbn = isbn.strip.gsub(/[\s\-]/, "")# {{{
@type = nil
@type_checked = false
end# }}}
# =set_isbn
def set_isbn(isbn)
@isbn = isbn# {{{
@type = nil
@type_checked = false
end# }}}
# =get_type
def get_type
unless @type_checked# {{{
len = @isbn.length
case len
when 10
if /^[0123457][0-9]{8}[0-9Xx]$/ =~ @isbn and check_isbn10
@type = :isbn10
end
when 13
if /^(978|979)[0-9]{10}/ =~ @isbn and check_isbn13
@type = :isbn13
end
end
@type_checked = true
end
@type
end# }}}
# =to_isbn10
def to_isbn10
if get_type == :isbn13# {{{
tmp = @isbn[3..11]
cd = get_check_digit_for_isbn10(tmp)
"#{tmp}#{cd}"
else
@isbn
end
end# }}}
# =to_isbn13
def to_isbn13
if get_type == :isbn10# {{{
tmp = "978#{@isbn[0..8]}"
cd = get_check_digit_for_isbn13(tmp)
"#{tmp}#{cd}"
else
@isbn
end
end# }}}
private
# =check_isbn10
def check_isbn10
cd = (@isbn[9..9].downcase == "x") ? 10 : @isbn[9..9].to_i# {{{
(cd == get_check_digit_for_isbn10(@isbn)) ? true : false
end# }}}
# =checK_isbn13
def check_isbn13
cd = @isbn[12..12].to_i# {{{
(cd == get_check_digit_for_isbn13(@isbn)) ? true : false
end# }}}
# =get_check_digit_for_isbn10
def get_check_digit_for_isbn10(isbn_str)
total = 0# {{{
isbn_str[0..8].split(//).each_with_index do |chr, index|
total += (10 - index) * chr.to_i
end
11 - (total % 11)
end# }}}
# =get_check_digit_for_isbn13
def get_check_digit_for_isbn13(isbn_str)
total = 0# {{{
isbn_str[0..11].split(//).each_with_index do |chr, index|
total += (index % 2 == 0 ? 1 : 3) * chr.to_i
end
res = 10 - (total % 10)
res_s = res.to_s
(res_s[res_s.length - 1].chr == "0") ? 0 : res
end# }}}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment