Class: Range

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/tracking/core_ext/range.rb

Constant Summary collapse

HOURS =

Adds some enumerable capabilities to Time ranges  (Normally they raise a “Can’t iterate time ranges”)

It works by assuming days while iterating the time range, but you can pass an optional parameter

3600
DAYS =
24*HOURS
DEFAULT_TIME_GRANULARITY =
DAYS

Instance Method Summary collapse

Instance Method Details

#collect(step = DEFAULT_TIME_GRANULARITY) ⇒ Object Also known as: map

Map / Collect over a Time range. A better implementation would be redefining ‘succ’ on Time. However, the ruby source code (At least 1.9.2-p0) hardcodes a check for Type,  so it would not work even if we provide our own ‘succ’ for Time.



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mongoid/tracking/core_ext/range.rb', line 17

def collect(step = DEFAULT_TIME_GRANULARITY)
  return super() unless first.is_a?(Time)

  return collect(step) {|c| c} unless block_given?

  # Pretty much a standard implementation of Map/Collect here
  ary, current, op = [], first, (exclude_end? ? :< : :<=)
  while current.send(op, last)
    ary << yield(current)
    current = current + step
  end 
  ary
end

#diff(granularity = DEFAULT_TIME_GRANULARITY) ⇒ Object

Diff returns the number of elements in the Range, much like ‘count’. Again, redefining ‘succ’ would be a better idea (see above). However, I think redefining ‘succ’ makes this O(n) while this is O(1)



35
36
37
38
39
40
41
42
# File 'lib/mongoid/tracking/core_ext/range.rb', line 35

def diff(granularity = DEFAULT_TIME_GRANULARITY)
  if first.is_a?(Time)
    @diff ||= (last - first) / granularity + (exclude_end? ? 0 : 1)
    @diff.to_i
  else
    @diff ||= count
  end
end

#hour_collect(&block) ⇒ Object Also known as: hour_map



49
50
51
# File 'lib/mongoid/tracking/core_ext/range.rb', line 49

def hour_collect(&block)
  collect(HOURS, &block)
end

#hour_diffObject

Helper methods for non default parameters



45
46
47
# File 'lib/mongoid/tracking/core_ext/range.rb', line 45

def hour_diff
  diff(HOURS)
end