Thursday, February 24, 2011

Ruby Light #1

The Ruby Light series is for Ruby code dumps that amuse me for one reason or another, possibly including commentary.

Here's the first one:

redirect_stdio.rb
# See: http://thinkingdigitally.com/archive/capturing-output-from-puts-in-ruby/

require 'stringio'

module Kernel
def capture_stdout(out = StringIO.new)
begin
$stdout = out
yield
ensure
$stdout = STDOUT
end

out
end

def use_my_stdin(instream)
begin
$stdin = instream
yield
ensure
$stdin = STDIN
end

instream
end
end


converter_test.rb
require 'lib/redirect_stdio'
require 'lib/converter.rb'

class ConverterTest < Test::Unit::TestCase
def test_convert
input_data = [
[ # headers
'rank', # index 0
'', # index 1
'', # index 2
'', # index 3
'', # index 4
'', # index 5
'name', # index 6
'category', # index 7
],
[ # data line 0
'123', # index 0
'', # index 1
'', # index 2
'', # index 3
'', # index 4
'', # index 5
'Foo', # index 6
'Bar', # index 7
],
]

converter = Converter.new
instream = StringIO.new input_data.map{|line| line.join("\t")}.join("\n")
output = capture_stdout do
use_my_stdin(instream) { converter.convert }
end

input_data[1..-1].each do |data|
assert_match /^#{data[6]} is rank #{data[0]} in #{data[7]}$/, output.string
end
end
end