class MongoModel::Types::DateTime

Public Instance Methods

cast(value) click to toggle source
# File lib/mongomodel/support/types/date_time.rb, line 7
def cast(value)
  case value
  when ::Array
    ::DateTime.civil(*value)
  when ::Hash
    cast("#{value[:date]} #{value[:time]}")
  when ::String
    cast(::DateTime.parse(value))
  else
    round_microseconds(value.to_datetime.utc) if value
  end
rescue
  nil
end
from_mongo(t) click to toggle source
# File lib/mongomodel/support/types/date_time.rb, line 26
def from_mongo(t)
  ::DateTime.civil(t.year, t.month, t.day, t.hour, t.min, t.sec + Rational(t.usec, 1000000)) if t
end
to_mongo(value) click to toggle source
# File lib/mongomodel/support/types/date_time.rb, line 22
def to_mongo(value)
  to_time(value.utc) if value
end

Private Instance Methods

round_microseconds(dt) click to toggle source
# File lib/mongomodel/support/types/date_time.rb, line 37
def round_microseconds(dt)
  ::DateTime.civil(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec + Rational(dt.sec_fraction).truncate(3))
end
to_time(dt) click to toggle source

Define our own to_time method as DateTime.to_time in ActiveSupport may return the DateTime object unchanged, whereas BSON expects an actual Time object.

# File lib/mongomodel/support/types/date_time.rb, line 33
def to_time(dt)
  ::Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec, dt.sec_fraction.to_f * 1000000)
end