Sha256: 8bb156f898635143d7a434d161eecd7b345f736f20feb10354cd89c5f8477c02

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

# frozen_string_literal: true

export_default :API

import '../extensions/core'
import '../extensions/fiber'

Exceptions  = import '../core/exceptions'
Supervisor  = import '../core/supervisor'
Throttler   = import '../core/throttler'

# Global API methods to be included in ::Object
module API
  def after(interval, &block)
    spin do
      sleep interval
      block.()
    end
  end

  def cancel_after(interval, &block)
    fiber = ::Fiber.current
    canceller = spin do
      sleep interval
      fiber.schedule Exceptions::Cancel.new
    end
    block.call
  ensure
    canceller.stop
  end

  def spin(&block)
    Fiber.spin(caller, &block)
  end
  alias_method :defer, :spin

  def spin_loop(&block)
    spin { loop(&block) }
  end

  def every(interval)
    timer = Gyro::Timer.new(interval, interval)
    loop do
      timer.await
      yield
    end
  end

  def move_on_after(interval, with_value: nil, &block)
    fiber = ::Fiber.current
    canceller = spin do
      sleep interval
      fiber.schedule Exceptions::MoveOn.new(nil, with_value)
    end
    block.call
  rescue Exceptions::MoveOn => e
    e.value
  ensure
    canceller.stop
  end

  def receive
    Fiber.current.receive
  end

  def sleep(duration = nil)
    return suspend unless duration

    timer = Gyro::Timer.new(duration, 0)
    timer.await
  end

  def supervise(&block)
    Supervisor.new.await(&block)
  end

  def throttled_loop(rate, count: nil, &block)
    throttler = Throttler.new(rate)
    if count
      count.times { throttler.(&block) }
    else
      loop { throttler.(&block) }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polyphony-0.26 lib/polyphony/core/global_api.rb
polyphony-0.25 lib/polyphony/core/global_api.rb