Sha256: 2a6ada55aaa2be3e6356575ed2ac40174ded954053c6b580176d12b5ee6735c3

Contents?: true

Size: 1.02 KB

Versions: 26

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

26 entries across 26 versions & 1 rubygems

Version Path
foobara-0.0.26 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.25 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.24 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.23 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.22 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.21 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.20 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.19 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.18 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.17 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.16 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.15 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.14 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.13 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.12 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.11 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.10 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.9 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.8 projects/builtin_types/src/date/casters/string.rb
foobara-0.0.7 projects/builtin_types/src/date/casters/string.rb