Sha256: e3dbe097f1c47760ee09ea7b319c3ab230ef81539696f08db840d9559ef38859

Contents?: true

Size: 682 Bytes

Versions: 3

Compression:

Stored size: 682 Bytes

Contents

# frozen_string_literal: true

module Polyphony
  # Implements general-purpose throttling
  class Throttler
    def initialize(rate)
      @rate = rate_from_argument(rate)
      @min_dt = 1.0 / @rate
    end

    def call(&block)
      @timer ||= Gyro::Timer.new(0, @min_dt)
      @timer.await
      block.call(self)
    end
    alias_method :process, :call

    def stop
      @timer&.stop
    end

    private

    def rate_from_argument(arg)
      return arg if arg.is_a?(Numeric)

      if arg.is_a?(Hash)
        return 1.0 / arg[:interval] if arg[:interval]
        return arg[:rate] if arg[:rate]
      end
      raise "Invalid rate argument #{arg.inspect}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
polyphony-0.40 lib/polyphony/core/throttler.rb
polyphony-0.39 lib/polyphony/core/throttler.rb
polyphony-0.38 lib/polyphony/core/throttler.rb