Class: Asynchro::Tracker

Inherits:
Object
  • Object
show all
Defined in:
lib/asynchro/tracker.rb

Instance Method Summary collapse

Constructor Details

#initializeTracker

Creates a new tracker. If a block is given, this block is called with the new instance as an argument, and the tracker is automatically run.



4
5
6
7
8
9
10
11
# File 'lib/asynchro/tracker.rb', line 4

def initialize
  @sequence = 0
  
  if (block_given?)
    instance_eval(&Proc.new)
    self.run!
  end
end

Instance Method Details

#finishObject

Executes this block when all the actions to be performed have checked in as finsished.



22
23
24
25
# File 'lib/asynchro/tracker.rb', line 22

def finish
  @finish ||= [ ]
  @finish << Proc.new
end

#perform(count = 1, &block) ⇒ Object

Performs an action. The supplied block will be called with a callback tracking Proc that should be triggered with ‘call` as many times as are specified in the `count` argument. When the correct number of calls have been made, this action is considered finished.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/asynchro/tracker.rb', line 31

def perform(count = 1, &block)
  @blocks ||= { }

  _sequence = @sequence += 1
  @blocks[_sequence] = count

  callback = lambda {
    if (@blocks[_sequence])
      if ((@blocks[_sequence] -=1) <= 0)
        @blocks.delete(_sequence)
      end
    
      if (@blocks.empty?)
        @finish and @finish.each(&:call)
      end
    end
  }
  
  @procs ||= [ ]
  @procs << lambda { block.call(callback) }
end

#run!Object

Runs through the tasks to perform for this tracker. Should only be called if this object is initialized without a supplied block as in that case, this would have been called already.



16
17
18
# File 'lib/asynchro/tracker.rb', line 16

def run!
  @procs and @procs.each(&:call)
end