Class: TrafficJam::LifetimeLimit

Inherits:
Limit
  • Object
show all
Defined in:
lib/traffic_jam/lifetime_limit.rb

Overview

This class represents a lifetime limit on an action, value pair. For example, if limiting the amount of money a user can transfer, the action could be :transfers and the value would be the user ID. The class exposes atomic increment operations and allows querying of the current amount used and amount remaining.

Instance Attribute Summary

Attributes inherited from Limit

#action, #max, #period, #value

Instance Method Summary collapse

Methods inherited from Limit

#decrement, #exceeded?, #flatten, #increment!, #limit_exceeded, #remaining, #reset

Constructor Details

#initialize(action, value, max: nil) ⇒ LifetimeLimit

Constructor takes an action name as a symbol, a maximum cap, and the period of limit. max and period are required keyword arguments.

Parameters:

  • action (Symbol)

    action name

  • value (String)

    limit target value

  • max (Integer) (defaults to: nil)

    required limit maximum

Raises:

  • (ArgumentError)

    if max is nil



15
16
17
# File 'lib/traffic_jam/lifetime_limit.rb', line 15

def initialize(action, value, max: nil)
  super(action, value, max: max, period: -1)
end

Instance Method Details

#increment(amount = 1, time: Time.now) ⇒ Boolean

Increment the amount used by the given number. Does not perform increment if the operation would exceed the limit. Returns whether the operation was successful.

Parameters:

  • amount (Integer) (defaults to: 1)

    amount to increment by

Returns:

  • (Boolean)

    true if increment succeded and false if incrementing would exceed the limit

Raises:

  • (ArgumentError)


26
27
28
29
30
31
# File 'lib/traffic_jam/lifetime_limit.rb', line 26

def increment(amount = 1, time: Time.now)
  raise ArgumentError, 'Amount must be an integer' if amount != amount.to_i
  return amount <= 0 if max.zero?

  !!run_script([amount.to_i, max])
end

#usedInteger

Return amount of limit used

Returns:

  • (Integer)

    amount used



36
37
38
39
40
# File 'lib/traffic_jam/lifetime_limit.rb', line 36

def used
  return 0 if max.zero?
  amount = redis.get(key) || 0
  [amount.to_i, max].min
end