discourse/lib/rate_limiter/on_create_record.rb

62 lines
1.6 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
class RateLimiter
# A mixin we can use on ActiveRecord Models to automatically rate limit them
# based on a SiteSetting.
#
# It expects a SiteSetting called `rate_limit_create_{model_name}` where
2013-02-25 11:42:20 -05:00
# `model_name` is the class name of your model, underscored.
2013-02-05 14:16:51 -05:00
#
module OnCreateRecord
# Over write to define your own rate limiter
def default_rate_limiter
return @rate_limiter if @rate_limiter.present?
limit_key = "create_#{self.class.name.underscore}"
max_setting = if user.new_user? and SiteSetting.has_setting?("rate_limit_new_user_#{limit_key}")
SiteSetting.send("rate_limit_new_user_#{limit_key}")
else
SiteSetting.send("rate_limit_#{limit_key}")
end
2013-02-25 11:42:20 -05:00
@rate_limiter = RateLimiter.new(user, limit_key, 1, max_setting)
2013-02-05 14:16:51 -05:00
end
def self.included(base)
2013-02-25 11:42:20 -05:00
base.extend(ClassMethods)
2013-02-05 14:16:51 -05:00
end
module ClassMethods
def rate_limit(limiter_method=nil)
2013-02-25 11:42:20 -05:00
2013-02-05 14:16:51 -05:00
limiter_method = limiter_method || :default_rate_limiter
2013-02-25 11:42:20 -05:00
self.after_create do
2013-12-13 01:04:45 -05:00
if rate_limiter = send(limiter_method)
rate_limiter.performed!
@performed ||= {}
@performed[limiter_method] = true
end
2013-02-05 14:16:51 -05:00
end
self.after_destroy do
2013-12-13 01:04:45 -05:00
if rate_limiter = send(limiter_method)
rate_limiter.rollback!
end
2013-02-05 14:16:51 -05:00
end
self.after_rollback do
2013-12-13 01:04:45 -05:00
if rate_limiter = send(limiter_method)
if @performed.present? && @performed[limiter_method]
rate_limiter.rollback!
@performed[limiter_method] = false
end
2013-02-05 14:16:51 -05:00
end
end
end
end
end
2013-02-25 11:42:20 -05:00
end