Module: Is::Async

Defined in:
lib/is/async.rb,
lib/is/async/timeout.rb,
lib/is/async/version.rb

Overview

public

Makes Ruby objects async-aware.

Defined Under Namespace

Classes: Timeout

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.versionObject



7
8
9
# File 'lib/is/async/version.rb', line 7

def self.version
  VERSION
end

Instance Method Details

#asyncObject

public

Call asynchronous behavior in a proper async context.



15
16
17
18
19
# File 'lib/is/async.rb', line 15

def async
  ::Async::Reactor.run do |task|
    yield task
  end
end

#awaitObject

public

Call asynchronous behavior synchronously in a proper async context.



23
24
25
26
27
28
29
30
31
# File 'lib/is/async.rb', line 23

def await
  if (task = ::Async::Task.current?)
    yield task
  else
    ::Async::Reactor.run { |task|
      yield task
    }.wait
  end
end

#sleep(seconds) ⇒ Object

public

Sleeps for ‘seconds` in a proper async context.



35
36
37
38
39
# File 'lib/is/async.rb', line 35

def sleep(seconds)
  await do |task|
    task.sleep(seconds)
  end
end

#timeout(seconds, &block) ⇒ Object

public

Call asynchonous behavior in a proper async context, wrapped in a timeout.

Raises ‘Is::Async::Timeout` if execution exceeds `seconds`.



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/is/async.rb', line 45

def timeout(seconds, &block)
  await do |task|
    if seconds && seconds > 0
      task.with_timeout(seconds, Timeout) do
        yield task
      end
    else
      yield task
    end
  end
end