Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Output Buffering with Ruby
A contents <<<
send this to a
this goes to a
a, I forgot to add this
<<<
B contents <<<
this goes to b
b, please
<<<
a = OutputBuffer.new
b = OutputBuffer.new
a.activate
puts "send this to a"
puts "this goes to a"
b.activate
puts "this goes to b"
puts "b, please"
a.activate
puts "a, I forgot to add this"
OutputBuffer::restore_default
puts "A contents <<<\n#{a}<<<"
puts "B contents <<<\n#{b}<<<"
namespace :example do
desc "Some important task"
task :notify, :send_email, :needs => [:environment] do |task, args|
args.with_defaults(:send_email => false)
buffer = OutputBuffer.new
puts "this would ordinarily be displayed right away"
buffer.stop
if args[:send_email]
# could send email here
# UserMailer.deliver_notification_mail(buffer)
puts "sending email <<<\n#{buffer}<<<"
else
puts buffer
end
end
end
require "stringio"
class OutputBuffer
def initialize
@buffer = StringIO.new
activate
end
def activate
$stdout = @buffer
end
def to_s
@buffer.rewind
@buffer.read
end
def stop
OutputBuffer::restore_default
end
def self.restore_default
$stdout = STDOUT
end
end
require "stringio"
buffer = StringIO.new
$stdout = buffer
puts "this would ordinarily be displayed right away"
$stdout = STDOUT
buffer.rewind
puts "the buffer captured: #{buffer.read}"
# => the buffer captured: this would ordinarily be displayed right away
$ rake example:notify
this would ordinarily be displayed right away
$ rake example:notify[true]
sending email <<<
this would ordinarily be displayed right away
<<<
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.