Module: MercadoPublicoCl::DateFormatter

Defined in:
lib/mercado_publico_cl/date_formatter.rb

Constant Summary collapse

ISO_REGEX =
/\A(\d{4})-(\d{2})-(\d{2})\z/
TWO_DIGIT_YEAR_REGEX =

“14/05/26”: Date.parse lo lee como yy/mm/dd (2014-05-26) — ambiguo.

%r{\A\d{1,2}([-/])\d{1,2}\1\d{2}\z}

Class Method Summary collapse

Class Method Details

.call(value) ⇒ Object

Raises:



11
12
13
14
15
16
# File 'lib/mercado_publico_cl/date_formatter.rb', line 11

def call(value)
  raise InvalidQueryError, "date is required" if value.nil?

  date = coerce(value)
  date.strftime("%d%m%Y")
end

.coerce(value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mercado_publico_cl/date_formatter.rb', line 18

def coerce(value)
  case value
  when Date, DateTime
    value.to_date
  when Time
    value.to_date
  when String
    parse_string(value)
  else
    raise InvalidQueryError, "invalid date value: #{value.inspect}"
  end
end

.parse_string(value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mercado_publico_cl/date_formatter.rb', line 31

def parse_string(value)
  stripped = value.strip
  raise InvalidQueryError, "invalid date string: #{value.inspect}" if stripped.empty?

  if TWO_DIGIT_YEAR_REGEX.match?(stripped)
    raise InvalidQueryError, "ambiguous two-digit year, use dd-mm-yyyy: #{value.inspect}"
  end

  if (m = ISO_REGEX.match(stripped))
    Date.new(m[1].to_i, m[2].to_i, m[3].to_i)
  else
    Date.parse(stripped)
  end
rescue ArgumentError
  raise InvalidQueryError, "invalid date string: #{value.inspect}"
end