Class: MotionRecord::Serialization::DateSerializer

Inherits:
BaseSerializer show all
Defined in:
lib/motion_record/serialization/date_serializer.rb

Constant Summary collapse

ISO8601_PATTERN =

ISO8601 pattern that only matches date strings

/\A\s*
(-?\d+)-(\d\d)-(\d\d)
\s*\z/ix

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseSerializer

#initialize

Constructor Details

This class inherits a constructor from MotionRecord::Serialization::BaseSerializer

Class Method Details

.date_from_iso8601(date_str) ⇒ Object

Parse an ISO8601 format date string.

date_str - the String date representation in ISO8601 format

Returns a Time object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/motion_record/serialization/date_serializer.rb', line 49

def self.date_from_iso8601(date_str)
  return nil unless date_str

  if (match = ISO8601_PATTERN.match(date_str))
    year = match[1].to_i
    mon  = match[2].to_i
    day  = match[3].to_i
    Time.utc(year, mon, day)
  else
    raise ArgumentError.new("invalid date: #{date_str.inspect}")
  end
end

.date_to_iso8601(time) ⇒ Object

Convert a Time object to an ISO8601 format date string.

time - the Time to convert

Returns the String representation



38
39
40
41
42
# File 'lib/motion_record/serialization/date_serializer.rb', line 38

def self.date_to_iso8601(time)
  return nil unless time
  
  "%04d-%02d-%02d" % [time.year, time.month, time.day]
end

Instance Method Details

#deserialize(value) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/motion_record/serialization/date_serializer.rb', line 24

def deserialize(value)
  case @column.type
  when :text
    self.class.date_from_iso8601(value)
  else
    raise "Can't deserialize #{value.inspect} from #{@column.type.inspect}"
  end
end

#serialize(value) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/motion_record/serialization/date_serializer.rb', line 15

def serialize(value)
  case @column.type
  when :text
    self.class.date_to_iso8601(value)
  else
    raise "Can't serialize #{value.inspect} to #{@column.type.inspect}"
  end
end