Class: MockThread

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

Defined Under Namespace

Classes: IsBlocked, IsDone

Instance Method Summary collapse

Instance Method Details

#make_queueObject



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

def make_queue
  MockQueue.new
end

#now(limit: 100, &block) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/mock-thread/mock-thread.rb', line 84

def now limit: 100, &block
  fiber = Fiber.new { instance_eval &block }
  val = nil
  count = 0
  update_before
  while fiber.alive?
    val = fiber.resume
    if val == :block
      count += 1
      if count > limit
        raise IsBlocked, "cannot now do that -- exceeded blocking limit"
      end
    else
      count = 0
    end
    update_after
  end
  val
end

#run(limit: 100) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mock-thread/mock-thread.rb', line 47

def run limit: 100
  loop do
    fiber = @will_do[0] or raise IsDone, "nothing to do"

    count = 0
    while fiber.alive?
      update_before
      val = fiber.resume
      update_after
      if fiber.alive? or @will_do.size > 1
        if val == :block
          count += 1
          if count > limit
            raise IsBlocked, "exceeded blocking limit"
          end
        else
          count = 0
          yield val if block_given?
        end
      else
        return val
      end
    end

    @will_do.shift
  end
end

#run_until_blocked(limit: 100, &block) ⇒ Object

Raises:



75
76
77
78
79
80
81
82
# File 'lib/mock-thread/mock-thread.rb', line 75

def run_until_blocked limit: 100, &block
  begin
    run limit: limit, &block
  rescue IsBlocked
    return
  end
  raise IsDone, "run_until_blocked never blocked"
end

#stepObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mock-thread/mock-thread.rb', line 32

def step
  loop do
    fiber = @will_do[0] or raise IsDone, "nothing to do"

    if fiber.alive?
      update_before
      val = fiber.resume
      update_after
      return val
    end

    @will_do.shift
  end
end

#update_afterObject

Override to update any state after running a step.



19
# File 'lib/mock-thread/mock-thread.rb', line 19

def update_after; end

#update_beforeObject

Override to update any state before running a step. For example, update part of the system that is not expressed by a mock thread, such as a component that processes what mock threads have sent to a queue.



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

def update_before; end

#will(&block) ⇒ Object

Schedule some code for deferred execution. For example:

c.will {foo}.will {bar}

The #foo and #bar methods of c will be called later.



27
28
29
30
# File 'lib/mock-thread/mock-thread.rb', line 27

def will &block
  (@will_do ||= []) << Fiber.new { instance_eval &block }
  self
end