1
0

rate_limitable.rb 727 B

123456789101112131415161718192021222324252627282930313233343536
  1. # frozen_string_literal: true
  2. module RateLimitable
  3. extend ActiveSupport::Concern
  4. def rate_limit=(value)
  5. @rate_limit = value
  6. end
  7. def rate_limit?
  8. @rate_limit
  9. end
  10. def rate_limiter(by, options = {})
  11. return @rate_limiter if defined?(@rate_limiter)
  12. @rate_limiter = RateLimiter.new(by, options)
  13. end
  14. class_methods do
  15. def rate_limit(options = {})
  16. after_create do
  17. by = public_send(options[:by])
  18. if rate_limit? && by&.local?
  19. rate_limiter(by, options).record!
  20. @rate_limit_recorded = true
  21. end
  22. end
  23. after_rollback do
  24. rate_limiter(public_send(options[:by]), options).rollback! if @rate_limit_recorded
  25. end
  26. end
  27. end
  28. end