Forum: Ruby Event-based stdout content capturing

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2160f04d1ee1ee303eb528580e8830d7?d=identicon&s=25 Daniel Vartanov (daniel-vartanov)
on 2009-02-03 12:20
(Received via mailing list)
Some legacy code produces output to STDOUT during execution. I need to
capture it on even-based model, something like the following:

capture the_legacy_code_lambda do |content|
  # do something with content each time something appears in STDOUT
end

how can I manage this? Are there any idioms?
E1d641bfe4071a5413bac781f06d3fd1?d=identicon&s=25 Sean O'halpin (sean)
on 2009-02-04 02:24
(Received via mailing list)
On Tue, Feb 3, 2009 at 11:19 AM, Daniel Vartanov
<daniel.vartanov@gmail.com> wrote:
> Some legacy code produces output to STDOUT during execution. I need to
> capture it on even-based model, something like the following:
>
> capture the_legacy_code_lambda do |content|
>  # do something with content each time something appears in STDOUT
> end
>
> how can I manage this? Are there any idioms?
>
>

You can reassign to the global $stdout object any object which
provides the method #write. You could use that to capture the output
something like this:

class Capture
  def initialize(*args, &block)
    @block = block
  end
  def write(txt)
    @block.call(txt)
  end
end

def capture(code, &block)
  old_stdout = $stdout
  begin
    $stdout = Capture.new(&block)
    code.call
  ensure
    $stdout = old_stdout
  end
end

def legacy_code
  puts "hello world"
  puts "me again"
  raise Exception, "Oh no!"
end

puts "start"
begin
  capture(proc { legacy_code }) do |txt|
    STDOUT.print "captured ["
    STDOUT.print txt
    STDOUT.puts "]"
    STDOUT.flush
  end
rescue Object => e
  puts "Got exception"
  raise
end
puts "end"

# $ ruby capture-stdout.rb
# start
# captured [hello world]
# captured [
# ]
# captured [me again]
# captured [
# ]
# Got exception
# capture-stdout.rb:23:in `legacy_code': Oh no! (Exception)
# etc.

Regards,
Sean
2160f04d1ee1ee303eb528580e8830d7?d=identicon&s=25 Daniel Vartanov (daniel-vartanov)
on 2009-02-04 06:25
(Received via mailing list)
Thank you very much, great idea! I missed in my mind, that puts just
uses global variable $stdout.
This topic is locked and can not be replied to.