diff --git a/lib/lisbn/lisbn.rb b/lib/lisbn/lisbn.rb index ca2fe29..bb2cee8 100644 --- a/lib/lisbn/lisbn.rb +++ b/lib/lisbn/lisbn.rb @@ -1,4 +1,21 @@ class Lisbn < String + + # Find an ISBN in a string of text + def scan_isbns + scan(/([\dX-]{10,})/i).flatten.map do |match| + isbn = self.class.new(match) + if isbn.valid? + if block_given? + yield isbn + else + isbn + end + else + nil + end + end.compact + end + # Returns a normalized ISBN form def isbn upcase.gsub(/[^0-9X]/, '') diff --git a/spec/lisbn_spec.rb b/spec/lisbn_spec.rb index 288e2c9..1d9fd6c 100644 --- a/spec/lisbn_spec.rb +++ b/spec/lisbn_spec.rb @@ -132,4 +132,28 @@ subject.split("7").should == ["9", "80000000002"] end end + + describe "#scan_isbns" do + it "should find two ISBN-13s in this sentence and return an array" do + isbns = Lisbn.new("Hi, I'm looking for 9780000000002 or 978-601-7002-01-5.").scan_isbns + isbns.should be_kind_of Array + isbns.size.should == 2 + isbns[0].should == "9780000000002" + isbns[1].isbn.should == "9786017002015" + end + + it "should take a block" do + isbns = 0 + Lisbn.new("Hi, I'm looking for 9780000000002 or 978-601-7002-01-5.").scan_isbns do |isbn| + isbn.should be_kind_of Lisbn + isbns += 1 + end + isbns.should == 2 + end + + it "should return an empty array when no ISBNs are present" do + Lisbn.new("nothing to see here").scan_isbns.should == [] + end + end + end