Class: RobotArmy::Loader

Inherits:
Object show all
Defined in:
lib/robot-army/loader.rb

Direct Known Subclasses

OfficerLoader

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#messengerObject

Returns the value of attribute messenger.



2
3
4
# File 'lib/robot-army/loader.rb', line 2

def messenger
  @messenger
end

Instance Method Details

#librariesObject



4
5
6
# File 'lib/robot-army/loader.rb', line 4

def libraries
  @libraries ||= []
end

#loadObject



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/robot-army/loader.rb', line 74

def load
  # create a soldier
  soldier = safely_or_die{ RobotArmy::Soldier.new(messenger) }
  
  # use the soldier to start listening to incoming commands
  # at this point everything has been loaded successfully, so we
  # don't have to exit if an exception is thrown
  loop do
    safely{ soldier.listen }
  end
end

#renderObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/robot-army/loader.rb', line 8

def render
  %{
    begin
      ##
      ## setup
      ##
      
      $TESTING = #{$TESTING.inspect}
      $stdout.sync = $stdin.sync = true
      #{libraries.map{|l| "require #{l.inspect}"}.join("\n")}
      
      
      ##
      ## local Robot Army objects to communicate with the parent
      ##
      
      loader = #{self.class.name}.new
      RobotArmy.upstream = RobotArmy::Messenger.new($stdin, $stdout)
      loader.messenger = RobotArmy.upstream
      loader.messenger.post(:status => 'ok')
      
      ##
      ## event loop
      ##
      
      loader.load
    rescue Object => e
      ##
      ## exception handler of last resort
      ##
      
      if defined?(RobotArmy::Exit) && e.is_a?(RobotArmy::Exit)
        # don't stomp on our own "let me out" exception
        exit(e.status)
      else
        # if we got here that means something up to and including loader.load
        # went unexpectedly wrong. this could be a missing library, or it 
        # could be a bug in Robot Army. either way we should report the error
        # back to the place we came from so that they may re-raise the exception
        
        # a little bit of un-DRY
        print Base64.encode64(Marshal.dump(:status => 'error', :data => e))+'|'
        exit(1)
      end
    end
  }
end

#safelyObject



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/robot-army/loader.rb', line 56

def safely
  begin
    return yield, true
  rescue RobotArmy::Exit
    # let RobotArmy::Exit through
    raise
  rescue Object => e
    messenger.post(:status => 'error', :data => e)
    return nil, false
  end
end

#safely_or_die(&block) ⇒ Object



68
69
70
71
72
# File 'lib/robot-army/loader.rb', line 68

def safely_or_die(&block)
  retval, success = safely(&block)
  exit(1) unless success
  return retval
end