Class: RobotArmy::IO

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

Class Method Details

.capture(stream) { ... } ⇒ String Also known as: silence

Redirects the named stream to a StringIO.

RobotArmy::IO.capture(:stdout) { puts "foo" } # => "foo\n"

RobotArmy::IO.silence(:stderr) { system "rm non-existent-file" }

Parameters:

  • stream (Symbol)

    The name of the stream to redirect (i.e. :stderr, :stdout).

Yields:

  • The block whose output we should capture.

Returns:

  • (String)

    The string result of the output produced by the block.



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/robot-army/io.rb', line 91

def capture(stream)
  begin
    stream = stream.to_s
    eval "$#{stream} = StringIO.new"
    yield
    result = eval("$#{stream}").string
  ensure 
    eval("$#{stream} = #{stream.upcase}")
  end

  result
end

.has_data?(stream) ⇒ Boolean

Determines whether the given stream has any data to be read.

Parameters:

  • stream (IO)

    The IO stream to check.

Returns:

  • (Boolean)

    true if stream has data to be read, false otherwise.



54
55
56
57
# File 'lib/robot-army/io.rb', line 54

def has_data?(stream)
  selected, _ = IO.select([stream], nil, nil, 0.5)
  return selected && !selected.empty?
end

.read_data(stream) ⇒ String

Reads immediately available data from the given stream.

# echo foo | ruby test.rb
RobotArmy::IO.read_data($stdin) # => "foo\n"

Parameters:

  • stream (IO)

    The IO stream to read from.

Returns:

  • (String)

    The data read from the stream.



70
71
72
73
74
# File 'lib/robot-army/io.rb', line 70

def read_data(stream)
  data = []
  data << stream.readpartial(1024) while has_data?(stream)
  return data.join
end

Instance Method Details

:nodoc:



20
21
22
# File 'lib/robot-army/io.rb', line 20

def print(*args) #:nodoc:
  post capture(:print, *args)
end

#puts(*args) ⇒ Object

:nodoc:



16
17
18
# File 'lib/robot-army/io.rb', line 16

def puts(*args) #:nodoc:
  post capture(:puts, *args)
end

#start_captureObject

Starts capturing output of the named stream.



6
7
8
# File 'lib/robot-army/io.rb', line 6

def start_capture
  eval "$#{name} = self"
end

#stop_captureObject

Stops capturing output of the named stream.



12
13
14
# File 'lib/robot-army/io.rb', line 12

def stop_capture
  eval "$#{name} = #{name.upcase}"
end

#write(*args) ⇒ Object

:nodoc:



24
25
26
# File 'lib/robot-army/io.rb', line 24

def write(*args) #:nodoc:
  post capture(:write, *args)
end