Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial extraction from validates_timeliness, using large regexps

  • Loading branch information...
commit af6d3967624b01af188ac28f57ab03e33c5d2227 0 parents
Adam Meehan authored
1  .rspec
@@ -0,0 +1 @@
+--color
119 benchmark.rb
@@ -0,0 +1,119 @@
+$:.unshift(File.expand_path('lib'))
+
+require 'date'
+require 'parsedate'
+require 'benchmark'
+require 'rubygems'
+require 'active_record'
+
+require 'timeliness'
+
+Time.zone = 'Australia/Melbourne'
+
+def parse(*args)
+ Timeliness::Parser.parse(*args)
+end
+
+n = 10000
+Benchmark.bm do |x|
+ x.report('timeliness - datetime') {
+ n.times do
+ parse("2000-01-04 12:12:12", :datetime)
+ end
+ }
+
+ x.report('timeliness - date') {
+ n.times do
+ parse("2000-01-04", :date)
+ end
+ }
+
+ x.report('timeliness - date as datetime') {
+ n.times do
+ parse("2000-01-04", :datetime)
+ end
+ }
+
+ x.report('timeliness - time') {
+ n.times do
+ parse("12:01:02", :time)
+ end
+ }
+
+ x.report('timeliness - invalid format datetime') {
+ n.times do
+ parse("20xx-01-04 12:12:12", :datetime)
+ end
+ }
+
+ x.report('timeliness - invalid format date') {
+ n.times do
+ parse("20xx-01-04", :date)
+ end
+ }
+
+ x.report('timeliness - invalid format time') {
+ n.times do
+ parse("12:xx:02", :time)
+ end
+ }
+
+
+ x.report('timeliness - invalid value datetime') {
+ n.times do
+ parse("2000-01-32 12:12:12", :datetime)
+ end
+ }
+
+ x.report('timeliness - invalid value date') {
+ n.times do
+ parse("2000-01-32", :date)
+ end
+ }
+
+ x.report('timeliness - invalid value time') {
+ n.times do
+ parse("12:61:02", :time)
+ end
+ }
+ x.report('Rails fast date/time') {
+ n.times do
+ "2000-01-04 12:12:12" =~ /\A(\d{4})-(\d{2})-(\d{2}) (\d{2})[\. :](\d{2})([\. :](\d{2}))?\Z/
+ arr = [$1, $2, $3, $3, $5, $6].map {|i| i.to_i }
+ Date.new(*arr[0..2])
+ Time.mktime(*arr)
+ end
+ }
+
+ x.report('Date._parse') {
+ n.times do
+ Date._parse("2000-01-04 12:12:12")
+ end
+ }
+
+ x.report('invalid Date._parse') {
+ n.times do
+ Date._parse("2000-01-32 12:12:12")
+ end
+ }
+
+ x.report('parsedate') {
+ n.times do
+ arr = ParseDate.parsedate("2000-01-04 12:12:12")
+ Date.new(*arr[0..2])
+ Time.mktime(*arr)
+ end
+ }
+
+ x.report('invalid parsedate') {
+ n.times do
+ arr = ParseDate.parsedate("garbage")
+ end
+ }
+
+ x.report('strptime') {
+ n.times do
+ DateTime.strptime("2000-01-04 12:12:12", '%Y-%m-%d %H:%M:%s')
+ end
+ }
+end
27 lib/timeliness.rb
@@ -0,0 +1,27 @@
+require 'date'
+require 'active_support/core_ext/module'
+require 'active_support/core_ext/hash'
+
+require 'timeliness/helpers'
+require 'timeliness/parser'
+
+module Timeliness
+ mattr_accessor :default_timezone
+ self.default_timezone = :utc
+
+ mattr_accessor :dummy_date_for_time_type
+ self.dummy_date_for_time_type = [ 2000, 1, 1 ]
+
+ # Set the threshold value for a two digit year to be considered last century
+ #
+ # Default: 30
+ #
+ # Example:
+ # year = '29' is considered 2029
+ # year = '30' is considered 1930
+ #
+ mattr_accessor :ambiguous_year_threshold
+ self.ambiguous_year_threshold = 30
+
+ delegate :parse, :add_formats, :remove_formats, :remove_us_formats, :to => Parser
+end
49 lib/timeliness/helpers.rb
@@ -0,0 +1,49 @@
+module Timeliness
+ module Helpers
+
+ def full_hour(hour, meridian)
+ hour = hour.to_i
+ return hour if meridian.nil?
+ if meridian.delete('.').downcase == 'am'
+ raise if hour == 0 || hour > 12
+ hour == 12 ? 0 : hour
+ else
+ hour == 12 ? hour : hour + 12
+ end
+ end
+
+ def unambiguous_year(year)
+ if year.length <= 2
+ century = Time.now.year.to_s[0..1].to_i
+ century -= 1 if year.to_i >= Timeliness.ambiguous_year_threshold
+ year = "#{century}#{year.rjust(2,'0')}"
+ end
+ year.to_i
+ end
+
+ def month_index(month)
+ return month.to_i if month.to_i.nonzero?
+ abbr_month_names.index(month.capitalize) || month_names.index(month.capitalize)
+ end
+
+ def month_names
+ I18n.t('date.month_names')
+ end
+
+ def abbr_month_names
+ I18n.t('date.abbr_month_names')
+ end
+
+ def microseconds(usec)
+ (".#{usec}".to_f * 1_000_000).to_i
+ end
+
+ def offset_in_seconds(offset)
+ sign = offset =~ /^-/ ? -1 : 1
+ parts = offset.scan(/\d\d/).map {|p| p.to_f }
+ parts[1] = parts[1].to_f / 60
+ (parts[0] + parts[1]) * sign * 3600
+ end
+
+ end
+end
346 lib/timeliness/parser.rb
@@ -0,0 +1,346 @@
+module Timeliness
+ # A date and time parsing library which allows you to add custom formats using
+ # simple predefined tokens. This makes it much easier to catalogue and customize
+ # the formats rather than dealing directly with regular expressions.
+ #
+ # Formats can be added or removed to customize the set of valid date or time
+ # string values.
+ #
+ module Parser
+ extend Helpers
+
+ mattr_reader :time_expressions, :date_expressions, :datetime_expressions
+
+ # Format tokens:
+ # y = year
+ # m = month
+ # d = day
+ # h = hour
+ # n = minute
+ # s = second
+ # u = micro-seconds
+ # ampm = meridian (am or pm) with or without dots (e.g. am, a.m, or a.m.)
+ # _ = optional space
+ # tz = Timezone abbreviation (e.g. UTC, GMT, PST, EST)
+ # zo = Timezone offset (e.g. +10:00, -08:00, +1000)
+ #
+ # All other characters are considered literal. You can embed regexp in the
+ # format but no guarantees that it will remain intact. If you avoid the use
+ # of any token characters and regexp dots or backslashes as special characters
+ # in the regexp, it may well work as expected. For special characters use
+ # POSIX character classes for safety.
+ #
+ # Repeating tokens:
+ # x = 1 or 2 digits for unit (e.g. 'h' means an hour can be '9' or '09')
+ # xx = 2 digits exactly for unit (e.g. 'hh' means an hour can only be '09')
+ #
+ # Special Cases:
+ # yy = 2 or 4 digit year
+ # yyyy = exactly 4 digit year
+ # mmm = month long name (e.g. 'Jul' or 'July')
+ # ddd = Day name of 3 to 9 letters (e.g. Wed or Wednesday)
+ # u = microseconds matches 1 to 6 digits
+ #
+ # Any other invalid combination of repeating tokens will be swallowed up
+ # by the next lowest length valid repeating token (e.g. yyy will be
+ # replaced with yy)
+
+ mattr_accessor :time_formats
+ @@time_formats = [
+ 'hh:nn:ss',
+ 'hh-nn-ss',
+ 'h:nn',
+ 'h.nn',
+ 'h nn',
+ 'h-nn',
+ 'h:nn_ampm',
+ 'h.nn_ampm',
+ 'h nn_ampm',
+ 'h-nn_ampm',
+ 'h_ampm'
+ ]
+
+ mattr_accessor :date_formats
+ @@date_formats = [
+ 'yyyy-mm-dd',
+ 'yyyy/mm/dd',
+ 'yyyy.mm.dd',
+ 'm/d/yy',
+ 'd/m/yy',
+ 'm\d\yy',
+ 'd\m\yy',
+ 'd-m-yy',
+ 'dd-mm-yyyy',
+ 'd.m.yy',
+ 'd mmm yy'
+ ]
+
+ mattr_accessor :datetime_formats
+ @@datetime_formats = [
+ 'yyyy-mm-dd hh:nn:ss',
+ 'yyyy-mm-dd h:nn',
+ 'yyyy-mm-dd h:nn_ampm',
+ 'yyyy-mm-dd hh:nn:ss.u',
+ 'm/d/yy h:nn:ss',
+ 'm/d/yy h:nn_ampm',
+ 'm/d/yy h:nn',
+ 'd/m/yy hh:nn:ss',
+ 'd/m/yy h:nn_ampm',
+ 'd/m/yy h:nn',
+ 'dd-mm-yyyy hh:nn:ss',
+ 'dd-mm-yyyy h:nn_ampm',
+ 'dd-mm-yyyy h:nn',
+ 'ddd, dd mmm yyyy hh:nn:ss tz', # RFC 822
+ 'ddd, dd mmm yyyy hh:nn:ss zo', # RFC 822
+ 'ddd mmm d hh:nn:ss zo yyyy', # Ruby time string
+ 'yyyy-mm-ddThh:nn:ssZ', # iso 8601 without zone offset
+ 'yyyy-mm-ddThh:nn:sszo' # iso 8601 with zone offset
+ ]
+
+ # All tokens available for format construction. The token array is made of
+ # regexp and key for format component mapping, if any.
+ #
+ mattr_accessor :format_tokens
+ @@format_tokens = {
+ 'ddd' => [ '\w{3,9}' ],
+ 'dd' => [ '\d{2}', :day ],
+ 'd' => [ '\d{1,2}', :day ],
+ 'mmm' => [ '\w{3,9}', :month ],
+ 'mm' => [ '\d{2}', :month ],
+ 'm' => [ '\d{1,2}', :month ],
+ 'yyyy' => [ '\d{4}', :year ],
+ 'yy' => [ '\d{4}|\d{2}', :year ],
+ 'hh' => [ '\d{2}', :hour ],
+ 'h' => [ '\d{1,2}', :hour ],
+ 'nn' => [ '\d{2}', :min ],
+ 'n' => [ '\d{1,2}', :min ],
+ 'ss' => [ '\d{2}', :sec ],
+ 's' => [ '\d{1,2}', :sec ],
+ 'u' => [ '\d{1,6}', :usec ],
+ 'ampm' => [ '[aApP]\.?[mM]\.?', :meridian ],
+ 'zo' => [ '[+-]\d{2}:?\d{2}', :offset ],
+ 'tz' => [ '[A-Z]{1,4}' ],
+ '_' => [ '\s?' ]
+ }
+
+ # Component argument values will be passed to the format method if matched in
+ # the time string. The key should match the key defined in the format tokens.
+ #
+ # The array consists of the position the value should be inserted in
+ # the time array, and the code to place in the time array.
+ #
+ # If the position is nil, then the value won't be put in the time array. If the
+ # code slot is empty, then just the raw value is used.
+ #
+ mattr_accessor :format_components
+ @@format_components = {
+ :year => [ 0, 'unambiguous_year(year)'],
+ :month => [ 1, 'month_index(month)'],
+ :day => [ 2 ],
+ :hour => [ 3, 'full_hour(hour, meridian ||= nil)'],
+ :min => [ 4 ],
+ :sec => [ 5 ],
+ :usec => [ 6, 'microseconds(usec)'],
+ :offset => [ 7, 'offset_in_seconds(offset)'],
+ :meridian => [ nil ]
+ }
+
+ @@type_wrapper = {
+ :date => [/\A/, nil],
+ :time => [nil , /\Z/],
+ :datetime => [/\A/, /\Z/]
+ }
+
+ mattr_accessor :date_regexp, :time_regexp, :datetime_regexp
+ class << self
+
+ def compile_format_expressions
+ @@time_expressions, @@time_regexp = compile_formats(@@time_formats)
+ @@date_expressions, @@date_regexp = compile_formats(@@date_formats)
+ @@datetime_expressions, @@datetime_regexp = compile_formats(@@datetime_formats)
+ end
+
+ def parse(value, type, options={})
+ return value unless value.is_a?(String)
+
+ time_array = _parse(value, type, options)
+ return nil if time_array.nil?
+
+ time_array[3..7] = nil if type == :date
+ make_time(time_array[0..7], options[:timezone_aware])
+ end
+
+ def make_time(time_array, timezone_aware=false)
+ # Enforce strict date part validity which Time class does not
+ return nil unless Date.valid_civil?(*time_array[0..2])
+
+ if timezone_aware
+ Time.zone.local(*time_array)
+ else
+ Time.time_with_datetime_fallback(Timeliness.default_timezone, *time_array)
+ end
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def _parse(string, type, options={})
+ options.reverse_merge!(:strict => true)
+
+ md = nil
+ set = expression_set(type, string)
+ expressions, regexp = set.find {|expressions, regexp| md = regexp.match(string) }
+
+ if md
+ captures = md.captures[1..-1]
+ last = options[:include_offset] ? 8 : 7
+ format ||= begin
+ index = captures.index(string)
+ expressions.rassoc(index).first
+ end
+ values = captures[(index+1)..(index+1+last)].compact
+ time_array = send(:"format_#{format}", *values)
+ time_array[0..2] = Timeliness.dummy_date_for_time_type if type == :time
+ time_array
+ end
+ rescue => e
+ nil
+ end
+
+ # Delete formats of specified type. Error raised if format not found.
+ #
+ def remove_formats(type, *remove_formats)
+ remove_formats.each do |format|
+ unless self.send("#{type}_formats").delete(format)
+ raise "Format #{format} not found in #{type} formats"
+ end
+ end
+ compile_format_expressions
+ end
+
+ # Adds new formats. Must specify format type and can specify a :before
+ # option to nominate which format the new formats should be inserted in
+ # front on to take higher precedence.
+ #
+ # Error is raised if format already exists or if :before format is not found.
+ #
+ def add_formats(type, *add_formats)
+ formats = send("#{type}_formats")
+ options = add_formats.extract_options!
+ before = options[:before]
+ raise "Format for :before option #{format} was not found." if before && !formats.include?(before)
+
+ add_formats.each do |format|
+ raise "Format #{format} is already included in #{type} formats" if formats.include?(format)
+
+ index = before ? formats.index(before) : -1
+ formats.insert(index, format)
+ end
+ compile_format_expressions
+ end
+
+ # Removes formats where the 1 or 2 digit month comes first, to eliminate
+ # formats which are ambiguous with the European style of day then month.
+ # The mmm token is ignored as its not ambiguous.
+ #
+ def remove_us_formats
+ us_format_regexp = /\Am{1,2}[^m]/
+ date_formats.reject! { |format| us_format_regexp =~ format }
+ datetime_formats.reject! { |format| us_format_regexp =~ format }
+ compile_format_expressions
+ end
+
+ private
+
+ # Generate regular expression from format string
+ def generate_format_regexp(string_format)
+ format = string_format.dup
+ format.gsub!(/([\.\\])/, '\\\\\1') # escapes dots and backslashes
+ found_tokens, token_order, value_token_count = [], [], 0
+
+ tokens = format_tokens.keys.sort {|a,b| a.size <=> b.size }.reverse
+
+ # Substitute tokens with numbered placeholder
+ tokens.each do |token|
+ regexp_str, arg_key = *format_tokens[token]
+ if format.gsub!(/#{token}/, "%<#{found_tokens.size}>")
+ if arg_key
+ regexp_str = "(#{regexp_str})"
+ value_token_count += 1
+ end
+ found_tokens << [regexp_str, arg_key]
+ end
+ end
+
+ # Replace placeholders with token regexps
+ format.scan(/%<(\d)>/).each {|token_index|
+ token_index = token_index.first
+ token = found_tokens[token_index.to_i]
+ format.gsub!("%<#{token_index}>", token[0])
+ token_order << token[1]
+ }
+
+ compile_format_method(token_order.compact, string_format)
+ return value_token_count, format
+ rescue
+ raise "The following format regular expression failed to compile: #{format}\n from format #{string_format}."
+ end
+
+ # Compiles a format method which maps the regexp capture groups to method
+ # arguments based on order captured. A time array is built using the argument
+ # values placed in the position defined by the component.
+ #
+ def compile_format_method(components, name)
+ values = [nil] * 7
+ components.each do |component|
+ position, code = *format_components[component]
+ values[position] = code || "#{component}.to_i" if position
+ end
+ class_eval <<-DEF
+ class << self
+ define_method(:"format_#{name}") do |#{components.join(',')}|
+ [#{values.map {|i| i || 'nil' }.join(',')}]
+ end
+ end
+ DEF
+ end
+
+ def compile_formats(formats)
+ regexp = ''
+ expressions = []
+ formats.inject(0) { |match_index, format|
+ token_count, regexp_string = generate_format_regexp(format)
+ regexp = "#{regexp}(#{regexp_string})|"
+ expressions << [ format, match_index ]
+ match_index += token_count + 1 # add one for wrapper capture
+ }
+ return expressions, Regexp.new("^(#{regexp.chop})$")
+ end
+
+ # Pick expression set and combine date and datetimes for
+ # datetime attributes to allow date string as datetime
+ def expression_set(type, string)
+ case type
+ when :date
+ [ [ date_expressions, date_regexp], [ datetime_expressions, datetime_regexp] ]
+ when :time
+ [ [ time_expressions, time_regexp], [ datetime_expressions, datetime_regexp] ]
+ when :datetime
+ # gives a speed-up for date string as datetime attributes
+ if string.length < 11
+ [ [ date_expressions, date_regexp], [ datetime_expressions, datetime_regexp] ]
+ else
+ [ [ datetime_expressions, datetime_regexp], [ date_expressions, date_regexp] ]
+ end
+ end
+ end
+
+ def wrap_regexp(regexp, type, strict=false)
+ type = strict ? :datetime : type
+ /#{@@type_wrapper[type][0]}#{regexp}#{@@type_wrapper[type][1]}/
+ end
+
+ end
+ end
+end
+
+Timeliness::Parser.compile_format_expressions
7 spec/spec_helper.rb
@@ -0,0 +1,7 @@
+require 'rspec'
+
+require 'timeliness'
+
+Rspec.configure do |c|
+ c.mock_with :rspec
+end
330 spec/timeliness/parser_spec.rb
@@ -0,0 +1,330 @@
+require 'spec_helper'
+
+describe Timeliness::Parser do
+
+ describe "format proc generator" do
+ it "should generate proc which outputs date array with values in correct order" do
+ generate_method('yyyy-mm-dd').call('2000', '1', '2').should == [2000,1,2,nil,nil,nil,nil]
+ end
+
+ it "should generate proc which outputs date array from format with different order" do
+ generate_method('dd/mm/yyyy').call('2', '1', '2000').should == [2000,1,2,nil,nil,nil,nil]
+ end
+
+ it "should generate proc which outputs time array" do
+ generate_method('hh:nn:ss').call('01', '02', '03').should == [nil,nil,nil,1,2,3,nil]
+ end
+
+ it "should generate proc which outputs time array with meridian 'pm' adjusted hour" do
+ generate_method('hh:nn:ss ampm').call('01', '02', '03', 'pm').should == [nil,nil,nil,13,2,3,nil]
+ end
+
+ it "should generate proc which outputs time array with meridian 'am' unadjusted hour" do
+ generate_method('hh:nn:ss ampm').call('01', '02', '03', 'am').should == [nil,nil,nil,1,2,3,nil]
+ end
+
+ it "should generate proc which outputs time array with microseconds" do
+ generate_method('hh:nn:ss.u').call('01', '02', '03', '99').should == [nil,nil,nil,1,2,3,990000]
+ end
+
+ it "should generate proc which outputs datetime array with zone offset" do
+ generate_method('yyyy-mm-dd hh:nn:ss.u zo').call('2001', '02', '03', '04', '05', '06', '99', '+10:00').should == [2001,2,3,4,5,6,990000,36000]
+ end
+ end
+
+ describe "validate regexps" do
+
+ describe "for time formats" do
+ format_tests = {
+ 'hh:nn:ss' => {:pass => ['12:12:12', '01:01:01'], :fail => ['1:12:12', '12:1:12', '12:12:1', '12-12-12']},
+ 'hh-nn-ss' => {:pass => ['12-12-12', '01-01-01'], :fail => ['1-12-12', '12-1-12', '12-12-1', '12:12:12']},
+ 'h:nn' => {:pass => ['12:12', '1:01'], :fail => ['12:2', '12-12']},
+ 'h.nn' => {:pass => ['2.12', '12.12'], :fail => ['2.1', '12:12']},
+ 'h nn' => {:pass => ['2 12', '12 12'], :fail => ['2 1', '2.12', '12:12']},
+ 'h-nn' => {:pass => ['2-12', '12-12'], :fail => ['2-1', '2.12', '12:12']},
+ 'h:nn_ampm' => {:pass => ['2:12am', '2:12 pm', '2:12 AM', '2:12PM'], :fail => ['1:2am', '1:12 pm', '2.12am']},
+ 'h.nn_ampm' => {:pass => ['2.12am', '2.12 pm'], :fail => ['1:2am', '1:12 pm', '2:12am']},
+ 'h nn_ampm' => {:pass => ['2 12am', '2 12 pm'], :fail => ['1 2am', '1 12 pm', '2:12am']},
+ 'h-nn_ampm' => {:pass => ['2-12am', '2-12 pm'], :fail => ['1-2am', '1-12 pm', '2:12am']},
+ 'h_ampm' => {:pass => ['2am', '2 am', '12 pm'], :fail => ['1.am', '12 pm', '2:12am']},
+ }
+ format_tests.each do |format, values|
+ it "should correctly validate times in format '#{format}'" do
+ regexp = generate_regexp(format)
+ values[:pass].each {|value| value.should match(regexp)}
+ values[:fail].each {|value| value.should_not match(regexp)}
+ end
+ end
+ end
+
+ describe "for date formats" do
+ format_tests = {
+ 'yyyy/mm/dd' => {:pass => ['2000/02/01'], :fail => ['2000\02\01', '2000/2/1', '00/02/01']},
+ 'yyyy-mm-dd' => {:pass => ['2000-02-01'], :fail => ['2000\02\01', '2000-2-1', '00-02-01']},
+ 'yyyy.mm.dd' => {:pass => ['2000.02.01'], :fail => ['2000\02\01', '2000.2.1', '00.02.01']},
+ 'm/d/yy' => {:pass => ['2/1/01', '02/01/00', '02/01/2000'], :fail => ['2/1/0', '2.1.01']},
+ 'd/m/yy' => {:pass => ['1/2/01', '01/02/00', '01/02/2000'], :fail => ['1/2/0', '1.2.01']},
+ 'm\d\yy' => {:pass => ['2\1\01', '2\01\00', '02\01\2000'], :fail => ['2\1\0', '2/1/01']},
+ 'd\m\yy' => {:pass => ['1\2\01', '1\02\00', '01\02\2000'], :fail => ['1\2\0', '1/2/01']},
+ 'd-m-yy' => {:pass => ['1-2-01', '1-02-00', '01-02-2000'], :fail => ['1-2-0', '1/2/01']},
+ 'd.m.yy' => {:pass => ['1.2.01', '1.02.00', '01.02.2000'], :fail => ['1.2.0', '1/2/01']},
+ 'd mmm yy' => {:pass => ['1 Feb 00', '1 Feb 2000', '1 February 00', '01 February 2000'],
+ :fail => ['1 Fe 00', 'Feb 1 2000', '1 Feb 0']}
+ }
+ format_tests.each do |format, values|
+ it "should correctly validate dates in format '#{format}'" do
+ regexp = generate_regexp(format)
+ values[:pass].each {|value| value.should match(regexp)}
+ values[:fail].each {|value| value.should_not match(regexp)}
+ end
+ end
+ end
+
+ describe "for datetime formats" do
+ format_tests = {
+ 'ddd mmm d hh:nn:ss zo yyyy' => {:pass => ['Sat Jul 19 12:00:00 +1000 2008'], :fail => []},
+ 'yyyy-mm-ddThh:nn:ss(?:Z|zo)' => {:pass => ['2008-07-19T12:00:00+10:00', '2008-07-19T12:00:00Z'], :fail => ['2008-07-19T12:00:00Z+10:00']},
+ }
+ format_tests.each do |format, values|
+ it "should correctly validate datetimes in format '#{format}'" do
+ regexp = generate_regexp(format)
+ values[:pass].each {|value| value.should match(regexp)}
+ values[:fail].each {|value| value.should_not match(regexp)}
+ end
+ end
+ end
+ end
+
+ # describe "parse" do
+ # it "should ignore time when extracting date and strict is false" do
+ # time_array = formats.parse('2000-02-01 12:13', :date)
+ # time_array.should == [2000,2,1,nil,nil,nil,nil]
+ # end
+
+ # it "should ignore time when extracting date from format with trailing year and strict is false" do
+ # time_array = formats.parse('01-02-2000 12:13', :date)
+ # time_array.should == [2000,2,1,nil,nil,nil,nil]
+ # end
+
+ # it "should ignore date when extracting time and strict is false" do
+ # time_array = formats.parse('2000-02-01 12:13', :time)
+ # time_array.should == [2000,1,1,12,13,nil,nil]
+ # end
+
+ # end
+
+ describe "_parse" do
+
+ it "should return time array from date string" do
+ time_array = formats._parse('12:13:14', :time, :strict => true)
+ time_array.should == [2000,1,1,12,13,14,nil]
+ end
+
+ it "should return nil if time hour is out of range for AM meridian" do
+ time_array = formats._parse('13:14 am', :time, :strict => true)
+ time_array.should == nil
+ time_array = formats._parse('00:14 am', :time, :strict => true)
+ time_array.should == nil
+ end
+
+ it "should return date array from time string" do
+ time_array = formats._parse('2000-02-01', :date, :strict => true)
+ time_array.should == [2000,2,1,nil,nil,nil,nil]
+ end
+
+ it "should return datetime array from string value" do
+ time_array = formats._parse('2000-02-01 12:13:14', :datetime, :strict => true)
+ time_array.should == [2000,2,1,12,13,14,nil]
+ end
+
+ it "should parse date string when type is datetime" do
+ time_array = formats._parse('2000-02-01', :datetime, :strict => false)
+ time_array.should == [2000,2,1,nil,nil,nil,nil]
+ end
+
+ it "should return zone offset when :include_offset option is true" do
+ time_array = formats._parse('2000-02-01T12:13:14-10:30', :datetime, :include_offset => true)
+ time_array.should == [2000,2,1,12,13,14,nil,-37800]
+ end
+
+ # context "with format option" do
+ # it "should return values if string matches specified format" do
+ # time_array = formats._parse('2000-02-01 12:13:14', :datetime, :format => 'yyyy-mm-dd hh:nn:ss')
+ # time_array.should == [2000,2,1,12,13,14,nil]
+ # end
+
+ # it "should return nil if string does not match specified format" do
+ # time_array = formats._parse('2000-02-01 12:13', :datetime, :format => 'yyyy-mm-dd hh:nn:ss')
+ # time_array.should be_nil
+ # end
+ # end
+
+ context "date with ambiguous year" do
+ it "should return year in current century if year below threshold" do
+ time_array = formats._parse('01-02-29', :date)
+ time_array.should == [2029,2,1,nil,nil,nil,nil]
+ end
+
+ it "should return year in last century if year at or above threshold" do
+ time_array = formats._parse('01-02-30', :date)
+ time_array.should == [1930,2,1,nil,nil,nil,nil]
+ end
+
+ it "should allow custom threshold" do
+ default = Timeliness.ambiguous_year_threshold
+ Timeliness.ambiguous_year_threshold = 40
+ time_array = formats._parse('01-02-39', :date)
+ time_array.should == [2039,2,1,nil,nil,nil,nil]
+ time_array = formats._parse('01-02-40', :date)
+ time_array.should == [1940,2,1,nil,nil,nil,nil]
+ Timeliness.ambiguous_year_threshold = default
+ end
+ end
+ end
+
+ describe "parse" do
+ it "should return time object for valid time string" do
+ parse("2000-01-01 12:13:14", :datetime).should be_kind_of(Time)
+ end
+
+ it "should return nil for time string with invalid date part" do
+ parse("2000-02-30 12:13:14", :datetime).should be_nil
+ end
+
+ it "should return nil for time string with invalid time part" do
+ parse("2000-02-01 25:13:14", :datetime).should be_nil
+ end
+
+ it "should return Time object when passed a Time object" do
+ parse(Time.now, :datetime).should be_kind_of(Time)
+ end
+
+ it "should convert time string into current timezone" do
+ Time.zone = 'Melbourne'
+ time = parse("2000-01-01 12:13:14", :datetime, :timezone_aware => true)
+ Time.zone.utc_offset.should == 10.hours
+ end
+
+ it "should return nil for invalid date string" do
+ parse("2000-02-30", :date).should be_nil
+ end
+
+ def parse(*args)
+ Timeliness::Parser.parse(*args)
+ end
+ end
+
+ describe "make_time" do
+ it "should create time using current timezone" do
+ time = Timeliness::Parser.make_time([2000,1,1,12,0,0])
+ time.zone.should == "UTC"
+ end
+
+ it "should create time using current timezone" do
+ Time.zone = 'Melbourne'
+ time = Timeliness::Parser.make_time([2000,1,1,12,0,0], true)
+ time.zone.should == "EST"
+ end
+ end
+
+ describe "removing formats" do
+ it "should remove format from format array" do
+ formats.remove_formats(:time, 'h.nn_ampm')
+ formats.time_formats.should_not include("h o'clock")
+ end
+
+ it "should not match time after its format is removed" do
+ validate('2.12am', :time).should be_true
+ formats.remove_formats(:time, 'h.nn_ampm')
+ validate('2.12am', :time).should be_false
+ end
+
+ it "should raise error if format does not exist" do
+ lambda { formats.remove_formats(:time, "ss:hh:nn") }.should raise_error()
+ end
+
+ after do
+ formats.time_formats << 'h.nn_ampm'
+ formats.compile_format_expressions
+ end
+ end
+
+ describe "adding formats" do
+ before do
+ formats.compile_format_expressions
+ end
+
+ it "should add format to format array" do
+ formats.add_formats(:time, "h o'clock")
+ formats.time_formats.should include("h o'clock")
+ end
+
+ it "should match new format after its added" do
+ validate("12 o'clock", :time).should be_false
+ formats.add_formats(:time, "h o'clock")
+ validate("12 o'clock", :time).should be_true
+ end
+
+ it "should add format before specified format and be higher precedence" do
+ formats.add_formats(:time, "ss:hh:nn", :before => 'hh:nn:ss')
+ validate("59:23:58", :time).should be_true
+ time_array = formats._parse('59:23:58', :time)
+ time_array.should == [2000,1,1,23,58,59,nil]
+ end
+
+ it "should raise error if format exists" do
+ lambda { formats.add_formats(:time, "hh:nn:ss") }.should raise_error()
+ end
+
+ it "should raise error if format exists" do
+ lambda { formats.add_formats(:time, "ss:hh:nn", :before => 'nn:hh:ss') }.should raise_error()
+ end
+
+ after do
+ formats.time_formats.delete("h o'clock")
+ formats.time_formats.delete("ss:hh:nn")
+ # reload class instead
+ end
+ end
+
+ describe "removing US formats" do
+ it "should validate a date as European format when US formats removed" do
+ time_array = formats._parse('01/02/2000', :date)
+ time_array.should == [2000,1,2,nil,nil,nil,nil]
+ formats.remove_us_formats
+ time_array = formats._parse('01/02/2000', :date)
+ time_array.should == [2000,2,1,nil,nil,nil,nil]
+ end
+
+ after do
+ # reload class
+ end
+ end
+
+
+ def formats
+ Timeliness::Parser
+ end
+
+ def validate(time_string, type)
+ !(formats.send("#{type}_regexp") =~ time_string).nil?
+ end
+
+ def generate_regexp(format)
+ # wrap in line start and end anchors to emulate extract values method
+ /\A#{formats.send(:generate_format_regexp, format).last}\Z/
+ end
+
+ def generate_regexp_str(format)
+ formats.send(:generate_format_regexp, format).last.inspect
+ end
+
+ def generate_method(format)
+ formats.send(:generate_format_regexp, format)
+ Timeliness::Parser.method(:"format_#{format}")
+ end
+
+ def delete_format(type, format)
+ formats.send("#{type}_formats").delete(format)
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.