Class: Compel::Coercion::DateType

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

Direct Known Subclasses

Date, DateTime, Time

Instance Attribute Summary collapse

Attributes inherited from Type

#options, #value

Instance Method Summary collapse

Methods inherited from Type

coerce, #coerce, human_name, #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_type.rb', line 6

def format
  @format
end

Instance Method Details

#build_error_resultObject



31
32
33
34
35
# File 'lib/compel/coercion/types/date_type.rb', line 31

def build_error_result
  custom_error = "'#{value}' is not a parsable #{klass.to_s.downcase} 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
26
27
28
29
# File 'lib/compel/coercion/types/date_type.rb', line 8

def coerce_value
  @format = default_format

  if options[:format]
    @format = options[:format][:value]
  end

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

  coerced = klass.strptime(value, format)

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

  build_error_result

  rescue
    build_error_result
end