~cytrogen/masto-fe

ref: 86ba8d3e14955841fed45b49114e06b7a3473ba4 masto-fe/app/models/concerns/rate_limitable.rb -rw-r--r-- 727 bytes
86ba8d3e — Claire Merge pull request #2368 from ClearlyClaire/glitch-soc/merge-upstream 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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