Permalink
Browse files

Convert ISBN10 to ISBN13, based on suggestion by Sitakanta Ray

  • Loading branch information...
1 parent 6accb08 commit d2098847374feba5277007d4a694b03a31aff2ba @swaroopch committed Jul 31, 2011
Showing with 31 additions and 3 deletions.
  1. +14 −3 app/controllers/book_controller.rb
  2. +17 −0 app/helpers/book_helper.rb
@@ -1,14 +1,21 @@
class BookController < ApplicationController
+ include BookHelper
+
respond_to :html
respond_to :json, :only => :view
def view
@isbn = canonicalize_isbn(params[:isbn])
- if @isbn.nil? || !is_isbn(@isbn)
+ unless @isbn.present? && (is_isbn10(@isbn) || is_isbn13(@isbn))
render :text => 'Not Found', :status => 404
return
end
+ if is_isbn10(@isbn)
+ redirect_to :action => "view", :isbn => isbn_10_to_13(@isbn)
+ return
+ end
+
@prices = Bookprice.new(:isbn => @isbn)
@stores = Rails.cache.fetch(@prices.cache_key)
@@ -49,8 +56,12 @@ def canonicalize_isbn(text)
end
end
- def is_isbn(text)
- /^[0-9]{9}[0-9xx]$/.match(text) or /^[0-9]{13}$/.match(text)
+ def is_isbn10(text)
+ /^[0-9]{9}[0-9xx]$/.match(text)
+ end
+
+ def is_isbn13(text)
+ /^[0-9]{13}$/.match(text)
end
end
View
@@ -1,2 +1,19 @@
module BookHelper
+ # http://refactormycode.com/codes/33-isbn10-to-isbn13#refactor_257
+ # isbn_10_to_13("0142000280") => 9780142000281
+ def isbn_10_to_13(isbn10)
+ match = %r|^([0-9]{9})[0-9xX]$|.match(isbn10)
+ return false if match.nil?
+
+ substring = match[1]
+
+ isbn10 = isbn10.chars.to_a
+
+ sum_of_digits = 38 +
+ 3 * (isbn10[0].to_i + isbn10[2].to_i + isbn10[4].to_i + isbn10[6].to_i + isbn10[8].to_i) +
+ isbn10[1].to_i + isbn10[3].to_i + isbn10[5].to_i + isbn10[7].to_i
+ check_digit = (10 - (sum_of_digits % 10)) % 10
+
+ return %|978#{substring}#{check_digit}|
+ end
end

0 comments on commit d209884

Please sign in to comment.