class Mongoid::Tracking::ReaderExtender

ReaderExtender is used in cases where we need to return an integer (class Numeric) while extending their contents. It would allow to perform advanced calculations in some situations:

Example:

a = visits.today   # Would return a number, but "extended" so that
                   # we can make a.hourly to get a detailed, hourly
                   # array of the visits.

b = visits.yesterday
c = a + b          # Here, in c, normally we would have a FixNum with
                   # the sum of a plus b, but if we extend the sum
                   # operation, we can additionaly sum the hourly
                   # array and return a new ReaderExtender c.

Public Class Methods

new(number, hours) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 22
def initialize(number, hours)
  @total = number
  @hours = hours
end

Public Instance Methods

+(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 66
def +(other)
  return @total + other unless other.is_a?(ReaderExtender)
  self.class.new(other + @total, @hours.zip(other.hourly).map!(&:sum))
end
<(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 51
def <(other)
  @total < other
end
<=(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 54
def <=(other)
  @total <= other
end
<=>(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 47
def <=>(other)
  @total <=> other
end
==(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 43
def ==(other)
  @total == other
end
>(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 58
def >(other)
  @total > other
end
as_json(options = nil) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 75
def as_json(options = nil)
  @total
end
coerce(other) click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 71
def coerce(other)
  [self.to_i, other]
end
hourly() click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 27
def hourly
  @hours
end
method_missing(name, *args, &blk) click to toggle source

Solution proposed by Yehuda Katz in the following Stack Overflow: stackoverflow.com/questions/1095789/sub-classing-fixnum-in-ruby

Basically we override our methods while proxying all missing methods to the underliying FixNum

# File lib/mongoid/tracking/reader_extender.rb, line 85
def method_missing(name, *args, &blk)
  ret = @total.send(name, *args, &blk)
  ret.is_a?(Numeric) ? ReaderExtender.new(ret, @hours) : ret
end
to_f() click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 35
def to_f
  @total.to_f
end
to_i() click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 39
def to_i
  @total.to_i
end
to_s() click to toggle source
# File lib/mongoid/tracking/reader_extender.rb, line 31
def to_s
  @total.to_s
end