Sha256: 34ef7ec828951ec696b62eb0484b819fd6c039080bbba8f5b084f7362f47ad34

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

module GluttonRatelimit

  def rate_limit symbol, executions, time_period, rl_class = AveragedThrottle
    rl = rl_class.new executions, time_period
    old_symbol = "#{symbol}_old".to_sym
    alias_method old_symbol, symbol
    define_method symbol do |*args|
      rl.wait
      self.send old_symbol, *args
    end
  end

  private
  # All the other classes extend this parent and are therefore
  # constructed in the same manner.
  class ParentLimiter
    attr_reader :executions

    def initialize executions, time_period
      @executions = executions
      @time_period = time_period
    end

    def times(num, &block)
      raise ArgumentError, "Code block expected"  if not block

      raise ArgumentError, "Parameter expected to be #{Integer.to_s} but found a #{num.class}."  unless num.kind_of?(Integer)
      num.times do
        wait
        yield
      end
    end
  end
end

dir = File.expand_path(File.dirname(__FILE__))
require File.join(dir, "glutton_ratelimit", "bursty_ring_buffer")
require File.join(dir, "glutton_ratelimit", "bursty_token_bucket")
require File.join(dir, "glutton_ratelimit", "averaged_throttle")

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
glutton_ratelimit-1.0.0 lib/glutton_ratelimit.rb