Guest User

Untitled

a guest
May 24th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. require 'digest/md5'
  2.  
  3. # Throttle arbituary operation. Once limit is reached it will raise a
  4. # Throttle::LimitExeeded exception.
  5. #
  6. # Example:
  7. #
  8. # Throttle.for("feed:#{request.remote_ip}", :max => 20, :in => 10.minutes) do
  9. # render :xml => Articles.all
  10. # end
  11. #
  12. # If you want to clear the timeout for the current block ( for example: fraud protection. Clear the throttle when
  13. # the submitted Credit Card was valid. ) your block can accept a yielded throttle object and call the clear method
  14. #
  15. # Throttle.for("cc:#{request.remote_ip}", :max => 20, :in => 10.minutes) do |throttle|
  16. # if am.pay(@credit_card)
  17. # throttle.clear
  18. # redirect_to :action => 'done'
  19. # end
  20. # end
  21. #
  22. class Throttle
  23. class LimitExceeded < StandardError
  24. end
  25.  
  26. def self.for(key, options = {})
  27. throttle = self.new(key, options)
  28. if ActionController::Base.perform_caching
  29. throttle.increment_counter
  30. end
  31.  
  32. yield throttle
  33. end
  34.  
  35. def initialize(key, options)
  36. @key = key.blank? ? nil : "throttle:#{Digest::MD5.hexdigest(key.to_s)}"
  37. @max, @timeout = options[:max].to_i, options[:in].to_i
  38. end
  39.  
  40. def increment_counter
  41. return if @key.blank?
  42.  
  43. count = Rails.cache.increment(@key)
  44.  
  45. if count.nil?
  46. Rails.cache.write @key, 1, :expires_in => @timeout
  47. elsif @max <= count
  48. raise LimitExceeded, "Too many requests for operation"
  49. end
  50. end
  51.  
  52. def clear
  53. return if @key.blank?
  54. return unless ActionController::Base.perform_caching
  55.  
  56. Rails.cache.delete @key
  57. true
  58. end
  59.  
  60. end
Add Comment
Please, Sign In to add comment