Class: Wands::JavaScript::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/wands/java_script/queue.rb

Overview

Asynchronous event queuing mechanism utilizing JavaScript’s Promise; since it uses JavaScript’s API, only objects that can be converted to JavaScript objects can pass through this queue.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeQueue

Returns a new instance of Queue.



15
16
17
18
# File 'lib/wands/java_script/queue.rb', line 15

def initialize
  @waiter = nil
  @buffer = []
end

Class Method Details

.wait_once {|queue| ... } ⇒ Object

Yields:

  • (queue)


9
10
11
12
13
# File 'lib/wands/java_script/queue.rb', line 9

def self.wait_once
  queue = new
  yield queue
  queue.pop
end

Instance Method Details

#popObject

The popped object is a JavaScript object. For example, when you push Ruby’s false, the pop method will return JS::True.



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/wands/java_script/queue.rb', line 37

def pop
  # message is received
  # return message
  return @buffer.shift unless @buffer.empty?

  # message is not received
  # set promise and wait
  resolve = nil
  promise = JS.global[:Promise].new { resolve = it }
  @waiter = resolve
  promise.await
end

#push(message) ⇒ Object Also known as: <<

Only objects that can be converted to JavaScript object can be pushed.

Raises:

  • (TypeError)


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/wands/java_script/queue.rb', line 21

def push(message)
  js_object = JS.try_convert(message)
  raise TypeError, "#{message.class} is not a JS::Object like object" unless js_object

  if @waiter
    @waiter.apply message
    @waiter = nil
  else
    @buffer << js_object
  end
end