Module: ThrottleMachines::ControllerHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/throttle_machines/controller_helpers.rb

Instance Method Summary collapse

Instance Method Details

#rate_limit_remaining(key = nil, limit:, period:) ⇒ Object



38
39
40
41
42
# File 'lib/throttle_machines/controller_helpers.rb', line 38

def rate_limit_remaining(key = nil, limit:, period:)
  key ||= default_throttle_key
  limiter = ThrottleMachines.limiter(key, limit: limit, period: period)
  limiter.remaining
end

#rate_limited?(key = nil, limit:, period:) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
# File 'lib/throttle_machines/controller_helpers.rb', line 32

def rate_limited?(key = nil, limit:, period:)
  key ||= default_throttle_key
  limiter = ThrottleMachines.limiter(key, limit: limit, period: period)
  !limiter.allow?
end

#throttle!(key = nil, limit:, period:, algorithm: :gcra) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/throttle_machines/controller_helpers.rb', line 14

def throttle!(key = nil, limit:, period:, algorithm: :gcra)
  key ||= default_throttle_key

  limiter = ThrottleMachines.limiter(key, limit: limit, period: period, algorithm: algorithm)

  render_rate_limited(limiter) unless limiter.allow?

  set_rate_limit_headers(limiter)
end

#with_throttle(key = nil, limit:, period:, &block) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/throttle_machines/controller_helpers.rb', line 24

def with_throttle(key = nil, limit:, period:, &block)
  key ||= default_throttle_key

  ThrottleMachines.limit(key, limit: limit, period: period, &block)
rescue ThrottledError => e
  render_rate_limited(e.limiter)
end