lib/rate_limiter.rb in rate_limiter-0.0.6 vs lib/rate_limiter.rb in rate_limiter-0.1.0
- old
+ new
@@ -1,63 +1,63 @@
+# frozen_string_literal: true
+
+require 'active_support/all'
+require 'active_record'
+
require 'rate_limiter/config'
-require 'rate_limiter/controller'
require 'rate_limiter/model'
+require 'rate_limiter/request'
+# Extend your ActiveRecord models with the ability to limit the rate at which
+# they are saved.
module RateLimiter
- def self.enabled=(value)
- RateLimiter.config.enabled = value
- end
+ class << self
+ # Return the RateLimiter singleton configuration object. This is for all
+ # threads.
+ def config
+ @config ||= Config.instance
+ yield @config if block_given?
+ @config
+ end
+ alias configure config
- def self.enabled?
- !!RateLimiter.config.enabled
- end
+ # Switches RateLimiter on or off, for all threads.
+ def enabled=(value)
+ config.enabled = value
+ end
- def self.enabled_for_controller=(value)
- rate_limiter_store[:request_enabled_for_controller] = value
- end
+ # Returns `true` if RateLimiter is on, `false if it is off. This is for all
+ # threads.
+ def enabled?
+ config.enabled
+ end
- def self.enabled_for_controller?
- !!rate_limiter_store[:request_enabled_for_controller]
+ # Gets the options local to the current request.
+ #
+ # If given a block the options passed in are set, the block is executed,
+ # previous options are restored, and the return value of the block is
+ # returned.
+ def request(options = nil, &block)
+ if options.nil? && !block_given?
+ Request
+ else
+ Request.with(options, &block)
+ end
+ end
end
-
- def self.timestamp_field=(field_name)
- RateLimiter.config.timestamp_field = field_name
- end
-
- def self.timestamp_field
- RateLimiter.config.timestamp_field
- end
-
- def self.source=(value)
- rate_limiter_store[:source] = value
- end
-
- def self.source
- rate_limiter_store[:source]
- end
-
- def self.controller_info=(value)
- rate_limiter_store[:controller_info] = value
- end
-
- def self.controller_info
- rate_limiter_store[:controller_info]
- end
-
- private
-
- def self.rate_limiter_store
- Thread.current[:rate_limiter] ||= { :request_enabled_for_controller => true }
- end
-
- def self.config
- @@config ||= RateLimiter::Config.instance
- end
end
+# See https://guides.rubyonrails.org/engines.html#what-are-on-load-hooks-questionmark
+# for more information on `on_load` hooks.
ActiveSupport.on_load(:active_record) do
include RateLimiter::Model
end
-ActiveSupport.on_load(:action_controller) do
- include RateLimiter::Controller
+# Load Rails controller extensions if RateLimiter is being used in a Rails
+# application.
+if defined?(::Rails)
+ if defined?(::Rails.application)
+ require 'rate_limiter/frameworks/rails'
+ else
+ Kernel.warn('RateLimiter has been loaded before Rails.')
+ end
end