Permalink
Browse files

The basic functionality is there.

  • Loading branch information...
1 parent e6e74e1 commit da037c9ced91f2c0a02dd05b9fa981a9770fcf3f @mhennemeyer committed May 26, 2008
Showing with 125 additions and 0 deletions.
  1. +36 −0 README
  2. +25 −0 lib/output_catcher.rb
  3. +61 −0 spec/output_catcher_spec.rb
  4. +3 −0 spec/spec_helper.rb
View
36 README
@@ -0,0 +1,36 @@
+= OutputCatcher
+
+by Matthias Hennemeyer <mhennemeyer@gmail.com>
+
+== Introduction
+
+OutputCatcher is available as a Rails plugin.
+It provides a way to capture the standard out($stdout) or standard error($stderr) of your code without pain
+and suppresses the output of the 'err' or 'out' stream.
+
+
+== Usage
+
+ OutputCatcher knows only two methods: .catch_err and .catch_out
+
+ To capture the stderr of your code:
+
+ err = OutputCatcher.catch_err do
+ $stderr << "error error"
+ end
+ err #=> "error error"
+
+
+ To capture the stdout of your code:
+
+ out = OutputCatcher.catch_out do
+ puts "Hello Hello"
+ end
+ out #=> "Hello Hello"
+
+== INSTALL:
+
+ $ ruby script/plugin install git://github.com/mhennemeyer/output_catcher.git
+
+
+Copyright (c) 2008 Matthias Hennemeyer, released under the MIT license
View
@@ -0,0 +1,25 @@
+class OutputCatcher
+ class << self
+
+ def catch_err(&block)
+ catch_io("err", &block)
+ end
+
+ def catch_io(post, &block)
+ original = eval("$std" + post)
+ fake = StringIO.new
+ eval("$std#{post} = fake")
+ begin
+ yield
+ ensure
+ eval("$std#{post} = original")
+ end
+ fake.string
+ end
+
+ def catch_out(&block)
+ catch_io("out", &block)
+ end
+
+ end
+end
@@ -0,0 +1,61 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe "OutputCatcher" do
+
+ describe ".catch_err" do
+ it "should run the code in the associated block" do
+ @var = 1
+ OutputCatcher.catch_err do
+ @var = 2
+ end
+ @var.should be(2)
+ end
+
+ it "should read $stderr and return it" do
+ for word in %w( Hello! Hallo! )
+ out = OutputCatcher.catch_err do
+ $stderr << word
+ end
+ out.should == word
+ end
+ end
+
+ it "should not output $stderr" do
+ out = OutputCatcher.catch_err do
+ OutputCatcher.catch_err do
+ $stderr << "Hello!"
+ end
+ end
+ out.should be_empty
+ end
+ end
+
+ describe ".catch_out" do
+ it "should run the code in the associated block" do
+ @var = 1
+ OutputCatcher.catch_out do
+ @var = 2
+ end
+ @var.should be(2)
+ end
+
+ it "should read $stdout and return it" do
+ for word in %w( Hello! Hallo! )
+ out = OutputCatcher.catch_out do
+ $stdout << word
+ end
+ out.should == word
+ end
+ end
+
+ it "should not output $stdout" do
+ out = OutputCatcher.catch_out do
+ OutputCatcher.catch_out do
+ $stdout << "Hello!"
+ end
+ end
+ out.should be_empty
+ end
+ end
+
+end
View
@@ -0,0 +1,3 @@
+require 'rubygems'
+require 'spec'
+require File.dirname(__FILE__) + '/../lib/testing.rb'

0 comments on commit da037c9

Please sign in to comment.