Class: HashCast::Casters::DateTimeCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/hashcast/casters/datetime_caster.rb

Class Method Summary collapse

Class Method Details

.cast(value, attr_name, options = {}) ⇒ Object



3
4
5
6
7
8
# File 'lib/hashcast/casters/datetime_caster.rb', line 3

def self.cast(value, attr_name, options = {})
  return value               if value.is_a?(DateTime)
  return value.to_datetime   if value.is_a?(Time)
  return cast_string(value)  if value.is_a?(String)
  raise HashCast::Errors::CastingError, "should be a datetime"
end

.cast_string(value) ⇒ Object



10
11
12
13
14
# File 'lib/hashcast/casters/datetime_caster.rb', line 10

def self.cast_string(value)
  DateTime.parse(value)
rescue ArgumentError => e
  raise HashCast::Errors::CastingError, "is invalid datetime"
end