You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
727 B

  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