diff options
author | Starfall <root@starfall.blue> | 2020-04-11 20:04:56 -0500 |
---|---|---|
committer | Starfall <root@starfall.blue> | 2020-04-11 20:04:56 -0500 |
commit | b107e4f771f036b214563764fcd95786f8016ee7 (patch) | |
tree | 22397105f42f30eceacdf84671d1c4d807c9dd73 /app/models/concerns/rate_limitable.rb | |
parent | 144ecfcfc7d9974117f1563084409a9558290a60 (diff) | |
parent | c47be5bd864a1f5244f35122ba7fae31a149c73d (diff) |
Merge branch 'glitch'
Diffstat (limited to 'app/models/concerns/rate_limitable.rb')
-rw-r--r-- | app/models/concerns/rate_limitable.rb | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/app/models/concerns/rate_limitable.rb b/app/models/concerns/rate_limitable.rb new file mode 100644 index 000000000..ad1b5e44e --- /dev/null +++ b/app/models/concerns/rate_limitable.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +module RateLimitable + extend ActiveSupport::Concern + + def rate_limit=(value) + @rate_limit = value + end + + def rate_limit? + @rate_limit + end + + def rate_limiter(by, options = {}) + return @rate_limiter if defined?(@rate_limiter) + + @rate_limiter = RateLimiter.new(by, options) + end + + class_methods do + def rate_limit(options = {}) + after_create do + by = public_send(options[:by]) + + if rate_limit? && by&.local? + rate_limiter(by, options).record! + @rate_limit_recorded = true + end + end + + after_rollback do + rate_limiter(public_send(options[:by]), options).rollback! if @rate_limit_recorded + end + end + end +end |