Sha256: b12d15ff2127a03a9665bfd4835d07e312decf2dd2b88f73f320b0dd375e5a87

Contents?: true

Size: 778 Bytes

Versions: 4

Compression:

Stored size: 778 Bytes

Contents

require 'date'

module SearchLingo
  module Parsers
    module MDY
      US_DATE = %r{(?<m>\d{1,2})/(?<d>\d{1,2})(?:/(?<y>\d{2}\d{2}?))?}

      def parse(term, relative_to: Date.today)
        term.match /\A#{US_DATE}\z/ do |m|
          return Date.parse "#{m[:y]}/#{m[:m]}/#{m[:d]}" if m[:y]

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

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

      module_function :parse
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
search_lingo-1.0.1 lib/search_lingo/parsers/mdy.rb
search_lingo-1.0.0 lib/search_lingo/parsers/mdy.rb
search_lingo-1.0.0.beta3 lib/search_lingo/parsers/mdy.rb
search_lingo-1.0.0.beta2 lib/search_lingo/parsers/mdy.rb