diff --git a/README.md b/README.md index 31943b9..ebd50fe 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ The reverse can also be accomplished with the output method. So pass in seconds => 4 minutes 30 seconds >> ChronicDuration.output(270, :format => :chrono) => 4:30 + >> ChronicDuration.output(270, :format => :chrono, :pad_to => :hours) + => 0:04:30 >> ChronicDuration.output(1299600, :weeks => true) => 2 wks 1 day 1 hr >> ChronicDuration.output(1299600, :weeks => true, :units => 2) diff --git a/lib/chronic_duration.rb b/lib/chronic_duration.rb index 5746f7c..9dbf0de 100644 --- a/lib/chronic_duration.rb +++ b/lib/chronic_duration.rb @@ -51,6 +51,7 @@ def output(seconds, opts = {}) opts[:format] ||= :default opts[:keep_zero] ||= false + opts[:pad_to] ||= :seconds years = months = weeks = days = hours = minutes = 0 @@ -130,7 +131,11 @@ def output(seconds, opts = {}) str.split(divider).map { |n| # add zeros only if n is an integer n.include?('.') ? ("%04.#{decimal_places}f" % n) : ("%02d" % n) - }.join(divider).gsub(/^(00:)+/, '').gsub(/^0/, '').gsub(/:$/, '') + }.join(divider).tap do |time| + [:years, :months, :days, :hours, :minutes, :seconds].index(opts[:pad_to]).times do + time.sub!(/^0+:/, '') + end + end.gsub(/^0/, '').gsub(/:$/, '') end joiner = '' end diff --git a/spec/lib/chronic_duration_spec.rb b/spec/lib/chronic_duration_spec.rb index 2e93fc9..e997178 100644 --- a/spec/lib/chronic_duration_spec.rb +++ b/spec/lib/chronic_duration_spec.rb @@ -197,6 +197,45 @@ end end + @pad_to_exemplars = { + (:years) => + { + :chrono => '0:00:00:00:00:00' + }, + (:months) => + { + :chrono => '0:00:00:00:00' + }, + (:days) => + { + :chrono => '0:00:00:00' + }, + (:hours) => + { + :chrono => '0:00:00' + }, + (:minutes) => + { + :chrono => '0:00' + }, + (:seconds) => + { + :chrono => '0' + }, + (nil) => + { + :chrono => '0' + } + } + + @pad_to_exemplars.each do |k, v| + v.each do |key, val| + it "should properly pad durations with a #{k.nil? ? "nil" : k}-level pad_to value using the #{key.to_s} format" do + ChronicDuration.output(0, :format => key, :pad_to => k).should == val + end + end + end + it "returns weeks when needed" do ChronicDuration.output(45*24*60*60, :weeks => true).should =~ /.*wk.*/ end