added microsecond/usec support to Redistat::Date

This commit is contained in:
2010-07-19 11:46:38 +03:00
parent 251ca5d90d
commit 7704c73b98
2 changed files with 17 additions and 8 deletions

View File

@@ -7,6 +7,7 @@ module Redistat
attr_accessor :hour
attr_accessor :min
attr_accessor :sec
attr_accessor :usec
def initialize(input)
if input.is_a?(::Time)
@@ -21,7 +22,7 @@ module Redistat
end
def to_time
::Time.local(@year, @month, @day, @hour, @min, @sec)
::Time.local(@year, @month, @day, @hour, @min, @sec, @usec)
end
def to_date
@@ -32,11 +33,16 @@ module Redistat
to_time.to_i
end
def to_string(depth = :sec)
def to_string(depth = nil)
depth ||= :sec
output = ""
[:year, :month, :day, :hour, :min, :sec].each_with_index do |current, i|
[:year, :month, :day, :hour, :min, :sec, :usec].each_with_index do |current, i|
break if self.send(current).nil?
output << self.send(current).to_s.rjust((i <= 0) ? 4 : 2, '0')
if current != :usec
output << self.send(current).to_s.rjust((i <= 0) ? 4 : 2, '0')
else
output << "." + self.send(current).to_s.rjust(6, '0')
end
break if current == depth
end
output
@@ -51,7 +57,7 @@ module Redistat
private
def from_time(input)
[:year, :month, :day, :hour, :min, :sec].each do |k|
[:year, :month, :day, :hour, :min, :sec, :usec].each do |k|
send("#{k}=", input.send(k))
end
end
@@ -60,7 +66,7 @@ module Redistat
[:year, :month, :day].each do |k|
send("#{k}=", input.send(k))
end
[:hour, :min, :sec].each do |k|
[:hour, :min, :sec, :usec].each do |k|
send("#{k}=", 0)
end
end

View File

@@ -5,7 +5,7 @@ describe Redistat::Date do
it "should initialize from Time object" do
now = Time.now
[Redistat::Date.new(now), now.to_rs].each do |rdate|
[:year, :month, :day, :hour, :min, :sec].each { |k| rdate.send(k).should == now.send(k) }
[:year, :month, :day, :hour, :min, :sec, :usec].each { |k| rdate.send(k).should == now.send(k) }
end
end
@@ -13,7 +13,7 @@ describe Redistat::Date do
today = Date.today
[Redistat::Date.new(today), today.to_rs].each do |rdate|
[:year, :month, :day].each { |k| rdate.send(k).should == today.send(k) }
[:hour, :min, :sec].each { |k| rdate.send(k).should == 0 }
[:hour, :min, :sec, :usec].each { |k| rdate.send(k).should == 0 }
end
end
@@ -54,6 +54,9 @@ describe Redistat::Date do
now = Time.now
[[now, Redistat::Date.new(now)], [today, Redistat::Date.new(today)]].each do |current, rdate|
props = [:year, :month, :day, :hour, :min, :sec, nil]
if rdate.usec > 0
rdate.to_s(:usec).should == props.map { |k| current.send(k).to_s.rjust(2, '0') if !k.nil? }.join + "." + current.usec.to_s.rjust(6, '0')
end
props.clone.each do
rdate.to_s(props.last).should == props.map { |k| current.send(k).to_s.rjust(2, '0') if !k.nil? }.join
props.pop