alhafoudh
12/1/2017 - 12:17 PM

throttler.rb

class Throttler
  attr_reader :period
  attr_reader :value
  attr_reader :block

  def initialize(period)
    @period = period
    @first_time = nil
    @value = nil
    @block = proc { }
  end

  def throttled(&block)
    @block = block if @block.nil?

    if @first_time.nil?
      @value = block.call
      @first_time = Time.now
    end

    current_time = Time.now
    @last_time = current_time unless last_time
    delta_time = current_time - last_time
    if delta_time > @period
      @value = block.call
      @last_time = current_time
    end

    value
  end

  def stop
    block.call
  end

  private

  attr_reader :last_time
end