Skip to content

Commit

Permalink
Using a regex to parse dates instead of attempting to parse and getti…
Browse files Browse the repository at this point in the history
…ng exception
  • Loading branch information
vicentemundim committed Mar 29, 2011
1 parent c65bb0d commit 093bff9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
6 changes: 4 additions & 2 deletions lib/mongoid/parsers/date_time_parser.rb
Expand Up @@ -2,12 +2,14 @@ module Mongoid
module QueryStringInterface
module Parsers
class DateTimeParser
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?([ \t]*)(Z?|[-+]\d{2}?(:?\d{2})?))$/

def parseable?(value, operator)
not parse(value).nil?
DATE_REGEX.match(value)
end

def parse(value)
value.to_time and Time.parse(value)
Time.parse(value)
rescue Exception
nil
end
Expand Down
32 changes: 18 additions & 14 deletions spec/mongoid/parsers/date_time_parser_spec.rb
@@ -1,27 +1,31 @@
require 'spec_helper'

describe Mongoid::QueryStringInterface::Parsers::DateTimeParser do
it "should be able to parse a valid date" do
should be_parseable('20101010', nil)
end

it "should be able to parse a valid date time" do
should be_parseable('2010-10-10T10:50:30', nil)
end

it "should not be able to parse a text" do
should_not be_parseable('Anything else', nil)
end

it "should not be able to parse an invalid date format" do
should_not be_parseable('20:asd:200 20/1/300', nil)
end

SAMPLE_DATES = [
"2010-10-10",
"2010-10-10T10:50:30",
"2010-10-10T10:50:30Z",
"2010-10-10T10:50:30-03:00",
"2010-10-10T10:50:30 -03:00",
"2010-10-10T10:50:30-0300",
"2010-10-10T10:50:30 -0300"
]

it "should parse a valid date" do
subject.parse('20101010').should == Time.parse('20101010')
end

it "should parse a valid date time" do
subject.parse('2010-10-10T10:50:30').should == Time.parse('2010-10-10T10:50:30')
SAMPLE_DATES.each do |time|
it "should be able to parse #{time}" do
should be_parseable(time, nil)
end

it "should parse #{time}" do
subject.parse(time).should == Time.parse(time)
end
end
end

0 comments on commit 093bff9

Please sign in to comment.