Class: Limited::Interval

Inherits:
Object
  • Object
show all
Defined in:
lib/limited/interval.rb

Overview

This represents a timespan within a limit counts after this timespan ends the limit should be reset

Constant Summary collapse

@@interval_lengths =

common lengths of the intervals and shortcuts for them

{
   second: 1,
   minute: 60,
     hour: 60 * 60,
      day: 60 * 60 * 24,
  endless: 1.0/0.0
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length) ⇒ Interval

initializes an interval by either supplying the length of the interval in seconds as an Numeric or by supplying one of the symbols :second, :minute, :hour or :day

Raises:

  • (ArgumentError)


28
29
30
31
32
33
# File 'lib/limited/interval.rb', line 28

def initialize(length)
  is_sym = length.is_a?(Symbol) and @@interval_lengths.has_key?(length)
  raise ArgumentError.new("Limited::Interval.length needs to be a Numeric or one of the symbols :second, :minute, :hour or :day") unless length.is_a?(Numeric) or is_sym
  @length = is_sym ? @@interval_lengths[length] : length
  reset_start
end

Instance Attribute Details

#last_startObject (readonly)

a timestamp when the last interval started



10
11
12
# File 'lib/limited/interval.rb', line 10

def last_start
  @last_start
end

#lengthObject (readonly)

the length of the interval in seconds



8
9
10
# File 'lib/limited/interval.rb', line 8

def length
  @length
end

Instance Method Details

#passed?Boolean

wheter the interval has finished

Returns:

  • (Boolean)


56
57
58
# File 'lib/limited/interval.rb', line 56

def passed?
  time_left == 0
end

#reset_startObject

start a new interval and reset the last_start variable



38
39
40
41
42
# File 'lib/limited/interval.rb', line 38

def reset_start
  now = Time.now
  @last_start = (now.to_f / @length).to_i * @length
  @last_start = 0 if @last_start.is_a?(Float) and @last_start.nan?
end

#time_leftObject

calculate the amount of seconds remaining in seconds for the interval to end

when the interval ended 0 is returned so this method never returns negative numbers



50
51
52
# File 'lib/limited/interval.rb', line 50

def time_left
  [0, (last_start.to_f + length - Time.now.to_f)].max
end