Module: EventMeter::TimeBuckets

Defined in:
lib/event_meter/time_buckets.rb

Constant Summary collapse

SIZES =
{
  minute: 60,
  hour: 3600
}.freeze

Class Method Summary collapse

Class Method Details

.between(from, to, size) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/event_meter/time_buckets.rb', line 36

def between(from, to, size)
  step = seconds(size)
  current = time(from, size)
  buckets = []

  while current < to
    buckets << current
    current += step
  end

  buckets
end

.id(time, size) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/event_meter/time_buckets.rb', line 10

def id(time, size)
  time = time.utc

  case normalize(size)
  when :minute
    time.strftime("%Y%m%d%H%M")
  when :hour
    time.strftime("%Y%m%d%H")
  end
end

.normalize(size) ⇒ Object

Raises:

  • (ArgumentError)


49
50
51
52
53
54
# File 'lib/event_meter/time_buckets.rb', line 49

def normalize(size)
  size = size.to_sym if size.respond_to?(:to_sym)
  return size if SIZES.key?(size)

  raise ArgumentError, "unsupported bucket size: #{size.inspect}"
end

.seconds(size) ⇒ Object



32
33
34
# File 'lib/event_meter/time_buckets.rb', line 32

def seconds(size)
  SIZES.fetch(normalize(size))
end

.time(value, size) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/event_meter/time_buckets.rb', line 21

def time(value, size)
  value = value.utc

  case normalize(size)
  when :minute
    Time.utc(value.year, value.month, value.day, value.hour, value.min)
  when :hour
    Time.utc(value.year, value.month, value.day, value.hour)
  end
end