BigDuration is a variant of Duration that supports years and months. Support for months is not accurate, as a month is assumed to be 30 days so use at your own risk.
Methods
each
months=
new
seconds
strftime
years=
Constants
YEAR | = | 60 * 60 * 24 * 30 * 12 |
MONTH | = | 60 * 60 * 24 * 30 |
Attributes
[R] | months | |
[R] | years |
Public Class methods
Similar to Duration.new except that BigDuration.new supports `:years’ and `:months’ and will also handle years and months correctly when breaking down the seconds.
[ + ]
# File lib/more/facets/duration.rb, line 366 def initialize(seconds_or_attr = 0) if seconds_or_attr.kind_of? Hash # Part->time map table. h =\ {:years => YEAR , :months => MONTH , :weeks => WEEK , :days => DAY , :hours => HOUR , :minutes => MINUTE, :seconds => SECOND} # Loop through each valid part, ignore all others. seconds = seconds_or_attr.inject(0) do |sec, args| # Grab the part of the duration (week, day, whatever) and the number of seconds for it. part, time = args # Map each part to their number of seconds and the given value. # {:weeks => 2} maps to h[:weeks] -- so... weeks = WEEK * 2 if h.key?(prt = part.to_s.to_sym) then sec + time * h[prt] else 0 end end else seconds = seconds_or_attr end @total, array = seconds.to_f.round, [] @seconds = [YEAR, MONTH, WEEK, DAY, HOUR, MINUTE].inject(@total) do |left, part| array << left / part; left % part end @years, @months, @weeks, @days, @hours, @minutes = array end
Public Instance methods
Similar to Duration#each except includes years and months in the interation.
[ + ]
# File lib/more/facets/duration.rb, line 413 def each [['years' , @years ], ['months' , @months ], ['weeks' , @weeks ], ['days' , @days ], ['hours' , @hours ], ['minutes' , @minutes], ['seconds' , @seconds]].each do |part, time| # Yield to block yield part, time end end
Set the number of months in the BigDuration.
[ + ]
# File lib/more/facets/duration.rb, line 445 def months=(n) initialize(:months => n, :seconds => @total - seconds(:months)) end
Derived from Duration#seconds, but supports `:years’ and `:months’ as well.
[ + ]
# File lib/more/facets/duration.rb, line 428 def seconds(part = nil) h = {:years => YEAR, :months => MONTH} if [:years, :months].include? part __send__(part) * h[part] else super(part) end end
BigDuration variant of Duration#strftime.
*Identifiers: BigDuration*
%y -- Number of years %m -- Number of months
[ + ]
# File lib/more/facets/duration.rb, line 406 def strftime(fmt) h = {'y' => @years, 'M' => @months} super(fmt.gsub(/%?%(y|M)/) { |match| match.size == 3 ? match : h[match[1..1]] }) end
Set the number of years in the BigDuration.
[ + ]
# File lib/more/facets/duration.rb, line 439 def years=(n) initialize(:years => n, :seconds => @total - seconds(:years)) end