From 251ca5d90d9167d3c39436d8c03dc65ba8b22fb7 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Mon, 19 Jul 2010 11:24:05 +0300 Subject: [PATCH] added integer input/output support to Redistat::Date so Unix timestamps can be used directly --- lib/redistat/date.rb | 18 ++++++++++++++++++ spec/date_spec.rb | 14 ++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/lib/redistat/date.rb b/lib/redistat/date.rb index 788ca25..1a74910 100644 --- a/lib/redistat/date.rb +++ b/lib/redistat/date.rb @@ -15,6 +15,8 @@ module Redistat from_date(input) elsif input.is_a?(::String) from_string(input) + elsif input.is_a?(::Fixnum) + from_integer(input) end end @@ -25,6 +27,10 @@ module Redistat def to_date ::Date.civil(@year, @month, @day) end + + def to_integer + to_time.to_i + end def to_string(depth = :sec) output = "" @@ -38,6 +44,7 @@ module Redistat alias :to_t :to_time alias :to_d :to_date + alias :to_i :to_integer alias :to_s :to_string @@ -58,6 +65,10 @@ module Redistat end end + def from_integer(input) + from_time(::Time.at(input)) + end + def from_string(input) from_time(::Time.parse(input)) end @@ -78,4 +89,11 @@ class Time Redistat::Date.new(self) end alias :to_rs :to_redistat +end + +class Fixnum + def to_redistat + Redistat::Date.new(self) + end + alias :to_rs :to_redistat end \ No newline at end of file diff --git a/spec/date_spec.rb b/spec/date_spec.rb index 43dd331..f25ef45 100644 --- a/spec/date_spec.rb +++ b/spec/date_spec.rb @@ -17,6 +17,14 @@ describe Redistat::Date do end end + it "should initialize from Fixnum object (UNIX Timestamp)" do + now = Time.now.to_i + time = Time.at(now) + [Redistat::Date.new(now), now.to_rs].each do |rdate| + [:year, :month, :day, :hour, :min, :sec].each { |k| rdate.send(k).should == time.send(k) } + end + end + it "should initialize from String object" do now = Time.now rdate = Redistat::Date.new(now.to_s) @@ -35,6 +43,12 @@ describe Redistat::Date do rdate.to_date.to_s.should == today.to_s end + it "should convert to Fixnum object (UNIX Timestamp)" do + now = Time.now + rdate = Redistat::Date.new(now) + rdate.to_i.should == now.to_i + end + it "should convert to string with correct depths" do today = Date.today now = Time.now