I'm writing a simple class to parse strings into relative dates.
module RelativeDate class InvalidString < StandardError; end class Parser REGEX = /([0-9]+)_(day|week|month|year)_(ago|from_now)/ def self.to_time(value) if captures = REGEX.match(value) captures[1].to_i.send(captures[2]).send(captures[3]) else raise InvalidString, "#{value} could not be parsed" end end end end The code seems to work fine.
Now when I try my specs I get a time difference only in year and month
require 'spec_helper' describe RelativeDate::Parser do describe "#to_time" do before do Timecop.freeze end ['day','week','month','year'].each do |type| it "should parse #{type} correctly" do RelativeDate::Parser.to_time("2_#{type}_ago").should == 2.send(type).ago RelativeDate::Parser.to_time("2_#{type}_from_now").should == 2.send(type).from_now end end after do Timecop.return end end end Output
..FF Failures: 1) RelativeDate::Parser#to_time should parse year correctly Failure/Error: RelativeDate::Parser.to_time("2_#{type}_ago").should == 2.send(type).ago expected: Wed, 29 Aug 2012 22:40:14 UTC +00:00 got: Wed, 29 Aug 2012 10:40:14 UTC +00:00 (using ==) Diff: @@ -1,2 +1,2 @@ -Wed, 29 Aug 2012 22:40:14 UTC +00:00 +Wed, 29 Aug 2012 10:40:14 UTC +00:00 # ./spec/lib/relative_date/parser_spec.rb:11:in `(root)' 2) RelativeDate::Parser#to_time should parse month correctly Failure/Error: RelativeDate::Parser.to_time("2_#{type}_ago").should == 2.send(type).ago expected: Sun, 29 Jun 2014 22:40:14 UTC +00:00 got: Mon, 30 Jun 2014 22:40:14 UTC +00:00 (using ==) Diff: @@ -1,2 +1,2 @@ -Sun, 29 Jun 2014 22:40:14 UTC +00:00 +Mon, 30 Jun 2014 22:40:14 UTC +00:00 # ./spec/lib/relative_date/parser_spec.rb:11:in `(root)' Finished in 0.146 seconds 4 examples, 2 failures Failed examples: rspec ./spec/lib/relative_date/parser_spec.rb:10 # RelativeDate::Parser#to_time should parse year correctly rspec ./spec/lib/relative_date/parser_spec.rb:10 # RelativeDate::Parser#to_time should parse month correctly The first one seems like a time zone issue but the other one is even a day apart? I'm really clueless on this one.