Created
October 7, 2014 13:43
-
-
Save blasterpal/0aaab3328578505be97b to your computer and use it in GitHub Desktop.
A simple before_filter-ish functionality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pry -r ./rate_limit_test.rb | |
| require './using_rate_limits' | |
| require './rate_limitable' | |
| f = UsingRateLimits.new | |
| require'pry';binding.pry | |
| f.some_method | |
| #using_rate_limits.rb | |
| require './rate_limitable' | |
| class UsingRateLimits | |
| include RateLimitable | |
| rate_limit :some_method, {max: 15, window: 900, user_context: lambda { self.user } } | |
| def some_method | |
| p "I'm original #{__method__} called!" | |
| end | |
| end | |
| #rate_limitable.rb | |
| module RateLimitable | |
| def self.included(base) | |
| base.extend RateLimitable | |
| include InstanceMethods | |
| end | |
| def initialize(*args) | |
| self._rate_limit_actions | |
| super(*args) | |
| end | |
| # register the methods | |
| def rate_limit(methud,options={}) | |
| @_limits ||= {} | |
| @_limits[methud.to_sym] = options | |
| end | |
| def _rate_limit_actions | |
| limits = self.class.instance_variable_get(:@_limits) | |
| p "rate limited actions for #{self} : #{limits}" | |
| limits.each do |methud,options| | |
| max = options.delete(:max) | |
| window = options.delete(:window) | |
| user_context = options.delete(:user_context) | |
| self.class.class_eval do | |
| alias_method "_rate_limit_#{methud}".to_sym, methud.to_sym | |
| define_method(methud.to_sym) do |*args| | |
| p "checking rate limits..." | |
| self.send "_rate_limit_#{methud}".to_sym(*args) | |
| end | |
| end | |
| end | |
| end | |
| module InstanceMethods | |
| def limit_action(methud) | |
| p "limit_action: #{methud}" | |
| end | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment