Class: Monolens::Coerce::DateTime

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

Constant Summary collapse

DEFAULT_FORMATS =
[
  nil
]

Instance Attribute Summary

Attributes included from Lens

#options

Instance Method Summary collapse

Methods included from Lens

#fail!, included, #initialize

Methods included from Lens::FetchSupport

#fetch_on

Instance Method Details

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



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/monolens/stdlib/coerce/date_time.rb', line 17

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

  is_string!(arg, world)

  date = nil
  first_error = nil
  formats = option(: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!("Invalid DateTime `#{arg}`", world) if first_error
end