Class: Compel::Coercion::Date

Inherits:
Type
  • Object
show all
Defined in:
lib/compel/coercion/types/date.rb

Instance Attribute Summary collapse

Attributes inherited from Type

#options, #value

Instance Method Summary collapse

Methods inherited from Type

#coerce, #initialize

Constructor Details

This class inherits a constructor from Compel::Coercion::Type

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format.



6
7
8
# File 'lib/compel/coercion/types/date.rb', line 6

def format
  @format
end

Instance Method Details

#build_error_resultObject



27
28
29
30
31
# File 'lib/compel/coercion/types/date.rb', line 27

def build_error_result
  custom_error = "'#{value}' is not a parsable date with format: #{format}"

  Result.new(nil, value, self.class, custom_error)
end

#coerce_valueObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/compel/coercion/types/date.rb', line 8

def coerce_value
  @format = options[:format] || '%Y-%m-%d'

  if value.is_a?(::Date)
    @value = value.strftime(format)
  end

  coerced = ::Date.strptime(value, format)

  if coerced.strftime(format) == value
    return coerced
  end

  build_error_result

  rescue
    build_error_result
end