Sha256: 2a6ada55aaa2be3e6356575ed2ac40174ded954053c6b580176d12b5ee6735c3

Contents?: true

Size: 1.02 KB

Versions: 27

Compression:

Stored size: 1.02 KB

Contents

module Foobara
  module BuiltinTypes
    module Date
      module Casters
        class String < Value::Caster
          def applicable?(value)
            value.is_a?(::String) && parse(value)
          end

          def applies_message
            "be a valid date string with year-month-day order"
          end

          def cast(string)
            parse(string)
          end

          private

          NOT_DELIMITED_REGEX = /\A(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})\z/
          DELIMITED_REGEX = /\A(?<year>\d{4,})(?<delimiter>[\/\\.|_:;-])(?<month>\d{1,2})\k<delimiter>(?<day>\d{1,2})\z/

          def parse(string)
            match = NOT_DELIMITED_REGEX.match(string) || DELIMITED_REGEX.match(string)

            if match
              year = match[:year].to_i
              month = match[:month].to_i
              day = match[:day].to_i

              if ::Date.valid_date?(year, month, day)
                ::Date.new(year, month, day)
              end
            end
          end
        end
      end
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
foobara-0.0.7 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.6 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.5 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.4 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.3 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.2 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.1 projects/builtin_types/src/date/casters/string.rb