Sha256: e9140ed1c892838662cb1d31594508a8fea67d499746ed1e9268ab9580167b64

Contents?: true

Size: 1.22 KB

Versions: 3

Compression:

Stored size: 1.22 KB

Contents

# encoding: utf-8
class Time
  # Functions to construct the MongoDB field key for trackers
  #
  # to_i_timestamp returns the computed UTC timestamp regardless of the
  # timezone.
  #
  # Examples:
  #    2011-01-01 00:00:00 UTC  ===> 14975
  #    2011-01-01 23:59:59 UTC  ===> 14975
  #    2011-01-02 00:00:00 UTC  ===> 14976
  # 
  # to_i_hour returns the hour for the date, again regardless of TZ
  #
  #    2011-01-01 00:00:00 UTC  ===> 0
  #    2011-01-01 23:59:59 UTC  ===> 23
  #
  ONEHOUR = 60 * 60
  ONEDAY = 24 * ONEHOUR

  def to_i_timestamp
    #Adding a fix for case where the 'quo' is being used instead of Fixnum's '/' operator
    (self.dup.utc.to_i / ONEDAY).to_i
  end

  def to_key_timestamp
    to_i_timestamp.to_s
  end

  def to_i_hour
    self.dup.utc.hour
  end

  def to_key_hour
    to_i_hour.to_s
  end

  # Returns an integer to use as MongoDB key
  def to_key
    "#{to_i_timestamp}.#{to_i_hour}"
  end

  def self.from_key(ts, h)
    Time.at(ts.to_i * ONEDAY + h.to_i * ONEHOUR)
  end

  # Returns a range to be enumerated using hours for the whole day
  def whole_day
    midnight = utc? ? Time.utc(year, month, day) : Time.new(year, month, day, 0, 0, 0, utc_offset)
    midnight...(midnight + ::Range::DAYS)
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
trackoid_mongoid4-0.1.4 lib/mongoid/tracking/core_ext/time.rb
trackoid_mongoid4-0.1.3 lib/mongoid/tracking/core_ext/time.rb
trackoid-0.4.0 lib/mongoid/tracking/core_ext/time.rb