Class: MockQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/mock-thread/mock-queue.rb

Defined Under Namespace

Classes: QueueEmptyError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(yield_on_push: false, yield_on_pop: false) ⇒ MockQueue

Returns a new instance of MockQueue.



8
9
10
11
12
# File 'lib/mock-thread/mock-queue.rb', line 8

def initialize yield_on_push: false, yield_on_pop: false
  @entries = []
  @yield_on_push = yield_on_push
  @yield_on_pop = yield_on_pop
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



4
5
6
# File 'lib/mock-thread/mock-queue.rb', line 4

def entries
  @entries
end

#yield_on_popObject (readonly)

Returns the value of attribute yield_on_pop.



6
7
8
# File 'lib/mock-thread/mock-queue.rb', line 6

def yield_on_pop
  @yield_on_pop
end

#yield_on_pushObject (readonly)

Returns the value of attribute yield_on_push.



5
6
7
# File 'lib/mock-thread/mock-queue.rb', line 5

def yield_on_push
  @yield_on_push
end

Instance Method Details

#empty?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/mock-thread/mock-queue.rb', line 14

def empty?
  entries.empty?
end

#popObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mock-thread/mock-queue.rb', line 26

def pop
  begin
    while @entries.empty?
      Fiber.yield :block
    end
  rescue FiberError => ex
    raise QueueEmptyError, "queue empty (#{ex.message})"
  end
  
  val = @entries.shift
  if yield_on_pop
    Fiber.yield([:pop, val]) rescue FiberError
  end
  val
end

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



18
19
20
21
22
23
# File 'lib/mock-thread/mock-queue.rb', line 18

def push val
  @entries << val
  if yield_on_push
    Fiber.yield([:push, val]) rescue FiberError
  end
end