Class: TrafficJam::LifetimeLimit
- 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
-
#increment(amount = 1, time: Time.now) ⇒ Boolean
Increment the amount used by the given number.
-
#initialize(action, value, max: nil) ⇒ LifetimeLimit
constructor
Constructor takes an action name as a symbol, a maximum cap, and the period of limit.
-
#used ⇒ Integer
Return amount of limit used.
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.
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.
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 |
#used ⇒ Integer
Return amount of limit 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 |