{ |one, step, back| } 1 of 1 article Syndicate: full/short

Ruby Module Spotlight: Session   27 Mar 04
[ print link all ]
Here’s a sweet little module from Ara T. Howard. It is called Session and will run a shell session under the control of a Ruby script. Standard output and standard error are captured by the session object and made available to the script.

How about a quick example …

  bash = Session::Bash.new
  stdout, stderr = bash.execute "ls"
  p stdout     # prints "trysession.rb\n"

The shell session created is persistent. Executing multiple commands in the session is like typing multiple lines into a real shell, the state is remembered from one command to the next. If you change the current directory, subsequent commands will execute in the new location. Environment variables set in the session will be remembered in later commands.

  bash = Session::Bash.new
  bash.execute "export GREETING=hi"
  out, err = bash.execute "echo $GREETING"
  p out    # print "hi\n"

If you pass an IO object to the session, it will append its output to that object.

  out = StringIO.new
  bash = Session::Bash.new
  bash.execute "ls", :stdout=>out
  bash.execute "ls ..", :stdout=>out
  p out  # prints the output from both "ls" commands.

One possible use of Session is to test command line scripts where you wish to check both standard output and standard error independently.

  class TestVersion < Test::Unit::TestCase
    def test_install
      out = StringIO.new
      bash = Session::Bash.new
      bash.execute "export GEMPATH=#{TESTDIR}"
      out, err = bash.execute "bin/gem --install testgem"
      assert_equals 0, bash.exit_status
      assert_equals "", err
      assert_equals EXPECTED_OUTPUT, out
      assert_test_gem_installed
    end
  end

You can find Session at www.codeforpeople.com/lib/ruby/session/


blog comments powered by Disqus

 

Formatted: 08-Sep-10 07:42
Feedback: jim@weirichhouse.org