Class: Monolens::Coerce::Date

Inherits:
Object
  • Object
show all
Includes:
Lens
Defined in:
lib/monolens/coerce/date.rb

Constant Summary collapse

DEFAULT_FORMATS =
[
  nil
]

Instance Attribute Summary

Attributes included from Lens

#options

Instance Method Summary collapse

Methods included from Lens

#initialize

Methods included from Lens::FetchSupport

#fetch_on

Instance Method Details

#call(arg, world = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/monolens/coerce/date.rb', line 12

def call(arg, world = {})
  return arg if arg.is_a?(::Date)

  is_string!(arg, world)

  date = nil
  first_error = nil
  formats = @options.fetch(:formats, DEFAULT_FORMATS)
  formats.each do |format|
    begin
      return date = strptime(arg, format)
    rescue ArgumentError => ex
      first_error ||= ex
    rescue ::Date::Error => ex
      first_error ||= ex
    end
  end

  fail!(first_error.message, world)
end

#strptime(arg, format = nil) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/monolens/coerce/date.rb', line 33

def strptime(arg, format = nil)
  if format.nil?
    ::Date.strptime(arg)
  else
    ::Date.strptime(arg, format)
  end
end