diff --git a/lib/epubinfo/models/date.rb b/lib/epubinfo/models/date.rb index 30c7ac7..d8481df 100644 --- a/lib/epubinfo/models/date.rb +++ b/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 diff --git a/lib/epubinfo/utils.rb b/lib/epubinfo/utils.rb index a6ad560..31bdd1b 100644 --- a/lib/epubinfo/utils.rb +++ b/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 diff --git a/spec/lib/epubinfo/models/date_spec.rb b/spec/lib/epubinfo/models/date_spec.rb index 845c72b..7e1ec51 100644 --- a/spec/lib/epubinfo/models/date_spec.rb +++ b/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 diff --git a/spec/lib/epubinfo/utils_spec.rb b/spec/lib/epubinfo/utils_spec.rb new file mode 100644 index 0000000..4cf5276 --- /dev/null +++ b/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 +