Module: Curbit::Controller::ClassMethods

Defined in:
lib/curbit.rb

Instance Method Summary collapse

Instance Method Details

#rate_limit(method, opts) ⇒ Object

  • max_calls - maximum number of calls allowed. Required.

  • time_limit - only :max_calls will be allowed within the specific time frame (in seconds). If :max_calls is reached within this time, the call will be halted. Required.

  • wait_time - The time to wait if :max_calls has been reached before being able to pass.

  • message - The message to render to the client if the call is being limited. The message will be rendered as a correspondingly formatted response with a default status if given a String. If the argument is a symbol, a method with the same name will be invoked with the specified wait_time (in seconds). The called method should take care of rendering the response.

  • status - The response status to set when the call is being limited.

Examples

class InviteController < ApplicationController

include Curbit::Controller

def validate
  # validate code
end

rate_limit :validate, :max_calls => 10,
                      :time_limit => 1.minute,
                      :wait_time => 1.minute,
                      :message => 'Too many attempts to validate your invitation code.  Please wait 1 minute before trying again.'

def invite
  # invite code
end

rate_limit :invite, :key => proc {|c| c.session[:userid]},
                     :max_calls => 2,
                     :time_limit => 30.seconds,
                     :wait_time => 1.minute

end



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/curbit.rb', line 50

def rate_limit(method, opts)

  return unless rate_limit_opts_valid?(opts)

  self.class_eval do
    define_method "rate_limit_#{method}" do
      rate_limit_filter(method, opts)
    end
  end
  self.before_filter("rate_limit_#{method}", :only => method)
end