about summary refs log tree commit diff
path: root/app/models/concerns/rate_limitable.rb
diff options
context:
space:
mode:
authorThibG <thib@sitedethib.com>2020-03-08 22:09:53 +0100
committerGitHub <noreply@github.com>2020-03-08 22:09:53 +0100
commit840b17e3444f9a68d3639f1ffeb326e8cb1e03b1 (patch)
tree8254538ed33f4c4b974b5379f3b5a0b489ba095a /app/models/concerns/rate_limitable.rb
parent13ef4d5fb0dbb66074f42df7989ae40509a4724f (diff)
parent9c2922958783f7e499cdda5bb874d6096e47eb0a (diff)
Merge pull request #1297 from ThibG/glitch-soc/merge-upstream
Merge upstream changes
Diffstat (limited to 'app/models/concerns/rate_limitable.rb')
-rw-r--r--app/models/concerns/rate_limitable.rb36
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