Permalink
Browse files

Better iso8601 format

  • Loading branch information...
1 parent 99ceacf commit 14983077c0159a457541def36554fd34f07c3051 @peleteiro committed Sep 20, 2010
Showing with 56 additions and 6 deletions.
  1. +1 −1 VERSION
  2. +17 −2 lib/duration.rb
  3. +2 −2 ruby-duration.gemspec
  4. +36 −1 test/test_duration.rb
View
@@ -1 +1 @@
-0.2.0
+0.2.1
View
@@ -64,9 +64,24 @@ def <=>(other)
# Formats a duration in ISO8601.
# @see http://en.wikipedia.org/wiki/ISO_8601#Durations
def iso8601
- format("P%wW%dDT%hH%mM%sS")
+ output = ''
+
+ if days > 0 || weeks > 0
+ output << 'P'
+ output << "#{weeks}W" if weeks > 0
+ output << "#{days}D" if days > 0
+ end
+
+ if seconds > 0 || minutes > 0 || hours > 0
+ output << 'T'
+ output << "#{hours}H" if hours > 0
+ output << "#{minutes}M" if minutes > 0
+ output << "#{seconds}S" if seconds > 0
+ end
+
+ output
end
-
+
# @return true if total is 0
def blank?
@total == 0
View
@@ -5,11 +5,11 @@
Gem::Specification.new do |s|
s.name = %q{ruby-duration}
- s.version = "0.2.0"
+ s.version = "0.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Jose Peleteiro"]
- s.date = %q{2010-09-16}
+ s.date = %q{2010-09-20}
s.description = %q{Duration type}
s.email = %q{jose@peleteiro.net}
s.extra_rdoc_files = [
View
@@ -36,10 +36,45 @@
end
describe "#iso_6801" do
- it "should" do
+ it "should format seconds" do
+ d = Duration.new(:seconds => 1)
+ assert_equal("T1S", d.iso8601)
+ end
+
+ it "should format minutes" do
+ d = Duration.new(:minutes => 1)
+ assert_equal("T1M", d.iso8601)
+ end
+
+ it "should format hours" do
+ d = Duration.new(:hours => 1)
+ assert_equal("T1H", d.iso8601)
+ end
+
+ it "should format days" do
+ d = Duration.new(:days => 1)
+ assert_equal("P1D", d.iso8601)
+ end
+
+ it "should format weeks" do
+ d = Duration.new(:weeks => 1)
+ assert_equal("P1W", d.iso8601)
+ end
+
+ it "should format only with given values" do
d = Duration.new(:weeks => 1, :days => 2, :hours => 3, :minutes => 4, :seconds => 5)
assert_equal("P1W2DT3H4M5S", d.iso8601)
+
+ d = Duration.new(:weeks => 1, :hours => 2, :seconds => 3)
+ assert_equal("P1WT2H3S", d.iso8601)
+
+ d = Duration.new(:weeks => 1, :days => 2)
+ assert_equal("P1W2D", d.iso8601)
+
+ d = Duration.new(:hours => 1, :seconds => 30)
+ assert_equal("T1H30S", d.iso8601)
end
+
end
describe "utilities methods" do

0 comments on commit 1498307

Please sign in to comment.