How can I capture Rake output when invoked from with a Ruby script?
Posted
by Adrian O'Connor
on Stack Overflow
See other posts from Stack Overflow
or by Adrian O'Connor
Published on 2009-09-08T13:39:15Z
Indexed on
2010/04/12
2:03 UTC
Read the original article
Hit count: 387
I am writing a web-based dev-console for Rails development. In one of my controller actions, I am calling Rake, but I am unable to capture any of the output that Rake generates. For example, here is some sample code, from the controller:
require 'rake'
require 'rake/rdoctask'
require 'rake/testtask'
require 'tasks/rails'
require 'stringio'
...
def show_routes
@results = capture_stdout { Rake.tasks['routes'].invoke }
# @results is nil -- the capture_stdout doesn't catpure anything that Rake generates
end
def capture_stdout
s = StringIO.new
$stdout = s
yield
s.string
ensure
$stdout = STDOUT
end
Does anybody know why I can't capture the Rake output? I've tried going through the Rake source, and I can't see where it fires a new process or anything, so I think I ought to be able to do this.
Many thanks! Adrian
I have since discovered the correct way to call Rake from inside Ruby that works much better:
Rake.application['db:migrate:redo'].reenable
Rake.application['db:migrate:redo'].invoke
Strangely, some rake tasks work perfectly now (routes), some capture the output the first time the run and after that are always blank (db:migrate:redo) and some don't seem to ever capture output (test). Odd.
© Stack Overflow or respective owner