Browse files

More robust date parsing

  • Loading branch information...
1 parent 1fd8a81 commit ac17ec89bb64c330c38fc2e2e61ee33ae3925883 @chdorner committed May 2, 2012
Showing with 40 additions and 6 deletions.
  1. +9 −5 lib/epubinfo/models/date.rb
  2. +11 −0 lib/epubinfo/utils.rb
  3. +2 −1 spec/lib/epubinfo/models/date_spec.rb
  4. +18 −0 spec/lib/epubinfo/utils_spec.rb
View
14 lib/epubinfo/models/date.rb
@@ -3,16 +3,20 @@
module EPUBInfo
module Models
class Date
- # Time ({http://idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.2.7 EPUB2 reference})
- # @return [Time]
- attr_accessor :time
+ # Date ({http://idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.2.7 EPUB2 reference})
+ # @return Date
+ attr_accessor :date
+ # Date as a string ({http://idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.2.7 EPUB2 reference})
+ # @return String
+ attr_accessor :date_str
# Event ({http://idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.2.7 EPUB2 reference})
- # @return [String]
+ # @return String
attr_accessor :event
# Should never be called directly, go through EPUBInfo.get
def initialize(node)
- self.time = Time.parse(node.content) rescue nil
+ self.date = Utils.parse_iso_8601_date(node.content) rescue nil
+ self.date_str = node.content
self.event = node.attribute('event').content rescue nil
end
View
11 lib/epubinfo/utils.rb
@@ -1,6 +1,17 @@
module EPUBInfo
module Utils
DC_NAMESPACE = { 'dc' => 'http://purl.org/dc/elements/1.1/' }
+
+ def self.parse_iso_8601_date(date_str)
+ case date_str.count('-')
+ when 0
+ Date.strptime(date_str, '%Y')
+ when 1
+ Date.strptime(date_str, '%Y-%m')
+ when 2
+ Date.strptime(date_str, '%Y-%m-%d')
+ end
+ end
end
end
View
3 spec/lib/epubinfo/models/date_spec.rb
@@ -4,7 +4,8 @@
describe '#initialize' do
subject { EPUBInfo::Models::Date.new(Nokogiri::XML(File.new('spec/support/xml/metamorphosis_metadata_epub2.opf')).css('metadata').xpath('.//dc:date').first) }
- its(:time) { should == Time.parse('2005-08-17') }
+ its(:date) { should == Date.new(2005, 8, 17) }
+ its(:date_str) { should == '2005-08-17' }
its(:event) { should == 'publication' }
end
View
18 spec/lib/epubinfo/utils_spec.rb
@@ -0,0 +1,18 @@
+require 'spec_helper'
+
+describe EPUBInfo::Utils do
+ describe '#parse_iso_8601_date' do
+ it 'should parse only year' do
+ EPUBInfo::Utils.parse_iso_8601_date('2012').should == Date.new(2012, 1, 1)
+ end
+
+ it 'should parse only year, and month' do
+ EPUBInfo::Utils.parse_iso_8601_date('2012-02').should == Date.new(2012, 2, 1)
+ end
+
+ it 'should parse year, month, and day' do
+ EPUBInfo::Utils.parse_iso_8601_date('2012-02-03').should == Date.new(2012, 2, 3)
+ end
+ end
+end
+

0 comments on commit ac17ec8

Please sign in to comment.