Sha256: 04aebd99db23d59f5c5c7b9d70d2d2e7ed99cd75024f48a7918cc1a6ef9722d0

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

require 'date'

module SearchLingo
  module Parsers # :nodoc:
    module MDY
      ##
      # Pattern for matching US-formatted date strings.
      #
      # The year may be two or four digits, or it may be omitted.
      US_DATE = %r{(?<m>\d{1,2})/(?<d>\d{1,2})(?:/(?<y>\d{2}\d{2}?))?}

      ##
      # Returns a +Date+ object for the date represented by +term+. Returns
      # +nil+ if +term+ can not be parsed.
      #
      # If the year has two digits, it will be implicitly expanded into a
      # four-digit year by +Date.parse+. Otherwise it will be used as is.
      #
      # If the year is omitted, it will be inferred using +relative_to+ as a
      # reference date. In this scenario, the resulting date will always be
      # less than or equal to the reference date. If +relative_to+ omitted, it
      # defaults to today's date.
      #
      # Available as both a class method and an instance method.
      def parse(term, relative_to: Date.today)
        term.match /\A#{US_DATE}\z/ do |m|
          return Date.parse '%d/%d/%d' % m.values_at(:y, :m, :d) if m[:y]

          ref   = relative_to
          day   = Integer(m[:d])
          month = Integer(m[:m])
          year  = if month < ref.month || month == ref.month && day <= ref.day
                    ref.year
                  else
                    ref.year - 1
                  end

          Date.new year, month, day
        end
      rescue ArgumentError
      end

      module_function :parse
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
search_lingo-2.0.0.pre1 lib/search_lingo/parsers/mdy.rb