Module: Mongoid::Fields::Serializable::Timekeeping
- Included in:
- Date, DateTime, Time, TimeWithZone
- Defined in:
- lib/mongoid/fields/serializable/timekeeping.rb
Overview
This module contains shared behaviour for date conversions.
Instance Method Summary collapse
-
#cast_on_read? ⇒ true
When reading the field do we need to cast the value? This holds true when times are stored or for big decimals which are stored as strings.
-
#convert_to_time(value) ⇒ Time
Convert the provided object to a UTC time to store in the database.
-
#deserialize(object) ⇒ Time
Deserialize this field from the type stored in MongoDB to the type defined on the model.
-
#serialize(object) ⇒ Time
Serialize the object from the type defined in the model to a MongoDB compatible object to store.
-
#strip_milliseconds(time) ⇒ Time
Strip the milliseconds off the time.
Instance Method Details
#cast_on_read? ⇒ true
When reading the field do we need to cast the value? This holds true when times are stored or for big decimals which are stored as strings.
18 |
# File 'lib/mongoid/fields/serializable/timekeeping.rb', line 18 def cast_on_read?; true; end |
#convert_to_time(value) ⇒ Time
Convert the provided object to a UTC time to store in the database.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/mongoid/fields/serializable/timekeeping.rb', line 72 def convert_to_time(value) time = Mongoid::Config.use_activesupport_time_zone? ? ::Time.zone : ::Time case value when ::String time.parse(value) when ::DateTime time.local(value.year, value.month, value.day, value.hour, value.min, value.sec) when ::Date time.local(value.year, value.month, value.day) when ::Array time.local(*value) else value end end |
#deserialize(object) ⇒ Time
Deserialize this field from the type stored in MongoDB to the type defined on the model.
31 32 33 34 35 36 37 38 39 |
# File 'lib/mongoid/fields/serializable/timekeeping.rb', line 31 def deserialize(object) return nil if object.blank? object = object.getlocal unless Mongoid::Config.use_utc? if Mongoid::Config.use_activesupport_time_zone? time_zone = Mongoid::Config.use_utc? ? 'UTC' : ::Time.zone object = object.in_time_zone(time_zone) end object end |
#serialize(object) ⇒ Time
Serialize the object from the type defined in the model to a MongoDB compatible object to store.
52 53 54 55 56 57 58 59 60 |
# File 'lib/mongoid/fields/serializable/timekeeping.rb', line 52 def serialize(object) return nil if object.blank? begin time = convert_to_time(object) strip_milliseconds(time).utc rescue ArgumentError raise Errors::InvalidTime.new(object) end end |
#strip_milliseconds(time) ⇒ Time
Durran: Why is this here? Still need time refactoring.
Strip the milliseconds off the time.
100 101 102 |
# File 'lib/mongoid/fields/serializable/timekeeping.rb', line 100 def strip_milliseconds(time) ::Time.at(time.to_i) end |