Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

Commit

Permalink
More robust date parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Christof Dorner committed May 3, 2012
1 parent 1fd8a81 commit ac17ec8
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 6 deletions.
14 changes: 9 additions & 5 deletions lib/epubinfo/models/date.rb
Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions 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

3 changes: 2 additions & 1 deletion spec/lib/epubinfo/models/date_spec.rb
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions 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.