# Copyright: Copyright (c) 2004 Nicolas Despres. All rights reserved. # Author: Nicolas Despres . # License: Gnu General Public License. # $LastChangedBy: polrop $ # $Id: dtime.rb 146 2005-02-01 11:02:42Z polrop $ require 'module/attr_once' class DTime def initialize(delta) @delta = delta.abs @min, @sec = @delta.divmod(60) @hour, @min = @min.floor.divmod(60) @day, @hour = @hour.divmod(24) end attr_reader :delta, :sec, :min, :hour, :day def to_s @delta.to_s.freeze end def inspect "#@day days #@hour hours #@min mins #@sec secs".freeze end def to_a [ @day, @hour, @min, @sec ].freeze end def to_i @delta.to_i end alias to_f delta def hash @delta.hash end def to_hash { :days => @day, :hours => @hour, :mins => @min, :secs => @sec }.freeze end def floor @delta.floor end def round @delta.round end def to_yaml(opts={}) ((@day != 0 ? "#@day days " : '') + (@hour != 0 ? "#@hour hours " : '') + (@min != 0 ? "#@min mins " : '') + "#@sec secs").to_yaml(opts) end attr_once :to_s, :inspect, :to_a, :to_i, :hash, :to_hash, :floor, :round, :to_yaml end # class DTime if defined? TEST_MODE or __FILE__ == $0 require 'test/unit/ui/yaml/testrunner' require 'yaml' class DTimeTest < Test::Unit::TestCase def test_simple d = DTime.new(260.33) assert_equal(260, d.delta.floor) assert_equal(20, d.sec.floor) assert_equal(4, d.min) assert_equal(0, d.hour) assert_equal(0, d.day) end def test_complex d = DTime.new(265678.42000) assert_equal(265678, d.delta.floor) assert_equal(58, d.sec.floor) assert_equal(47, d.min) assert_equal(1, d.hour) assert_equal(3, d.day) assert_equal([ 3, 1, 47 ], d.to_a[0..2]) assert_equal(58, d.to_a[3].floor) h = d.to_hash assert_equal(3, h[:days]) assert_equal(1, h[:hours]) assert_equal(47, h[:mins]) assert_equal(58, h[:secs].floor) end def test_conversion d = DTime.new(260.75) assert_equal('260.75', d.to_s) assert_equal('0 days 0 hours 4 mins 20.75 secs', d.inspect) assert_equal(260, d.to_f.floor) assert_equal(260, d.to_i) assert_equal(260, d.floor) assert_equal(261, d.round) end def test_negative d = DTime.new(-265678.42000) assert_equal(265678, d.delta.floor) assert_equal(58, d.sec.floor) assert_equal(47, d.min) assert_equal(1, d.hour) assert_equal(3, d.day) end def test_marshal d = DTime.new(-265678.42000) assert_equal(d.floor, Marshal.load(Marshal.dump(d)).floor) end def test_to_yaml d = DTime.new(265678.42000) assert_equal('--- 3 days 1 hours 47 mins 58.4199999999837 secs', d.to_yaml) d = DTime.new(5678.42000) assert_equal('--- 1 hours 34 mins 38.4200000000001 secs', d.to_yaml) d = DTime.new(158.42000) assert_equal('--- 2 mins 38.42 secs', d.to_yaml) d = DTime.new(58.42000) assert_equal('--- 58.42 secs', d.to_yaml) end end # class DTimeTest end