123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Extensions::Time::ClassMethods

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Defined in: lib/mongoid/extensions/time.rb

Instance Method Summary

Instance Method Details

#demongoize(object) ⇒ Time | nil

Convert the object from its mongo friendly ruby type to this type.

Examples:

Demongoize the object.

Time.demongoize(object)

Parameters:

  • object (Time)

    The time from Mongo.

Returns:

  • (Time | nil)

    The object as a time.

[ GitHub ]

  
# File 'lib/mongoid/extensions/time.rb', line 41

def demongoize(object)
  return if object.blank?
  time = if object.acts_like?(:time)
    Mongoid::Config.use_utc? ? object : object.getlocal
  elsif object.acts_like?(:date)
    ::Date.demongoize(object).to_time
  elsif object.is_a?(String)
    begin
      object.__mongoize_time__
    rescue ArgumentError
      nil
    end
  elsif object.is_a?(BSON::Timestamp)
    ::Time.at(object.seconds)
  end

  return if time.nil?

  time.in_time_zone(Mongoid.time_zone)
end

#mongoize(object) ⇒ Time | nil

Turn the object from the ruby type we deal with to a Mongo friendly type.

Examples:

Mongoize the object.

Time.mongoize("2012-1-1")

Parameters:

  • object (Object)

    The object to mongoize.

Returns:

  • (Time | nil)

    The object mongoized or nil.

[ GitHub ]

  
# File 'lib/mongoid/extensions/time.rb', line 71

def mongoize(object)
  return if object.blank?
  begin
    time = object.respond_to?(:__mongoize_time__) ? object.__mongoize_time__ : nil
  rescue ArgumentError
    return
  end

  if time.acts_like?(:time)
    if object.respond_to?(:sec_fraction)
      ::Time.at(time.to_i, object.sec_fraction * 10**6).utc
    elsif time.respond_to?(:subsec)
      ::Time.at(time.to_i, time.subsec * 10**6).utc
    else
      ::Time.at(time.to_i, time.usec).utc
    end
  end
end