Skip to content

Using Named IOs

mosop edited this page Jan 31, 2017 · 6 revisions

Each command instance has a named IO container, a Cli::IoHash object. You can get a target IO object by a name from the container.

By default, the following named IOs are automatically set:

  • :out : STDOUT. In the test environment, a Cli::Ios::Pipe object.
  • :err : STDERR. In the test environment, a Cli::Ios::Pipe object.

To access a named IO container in a running context, use the #io method. To access each named IO, call the container's [] method with an IO's name.

class Smiley < Cli::Command
  def run
    io[:out].puts ":)"
  end
end

Smiley.run # prints ":)" to STDOUT

Helper Methods

For convenience, there are the following methods to access named IOs:

  • #puts
  • #print
  • #out
  • #err

#puts and #print

Calls the :out IO's puts and print methods.

class Smiley < Cli::Command
  def run
    puts ":)" # equivalent to io[:out].puts ":)"
  end
end

#out

Gets the :out IO.

class Smiley < Cli::Command
  def run
    out.puts ":)" # equivalent to io[:out].puts ":)"
  end
end

#err

Gets the :err IO.

class Frown < Cli::Command
  def run
    err.puts ":(" # equivalent to io[:err].puts ":("
  end
end

Setting Custom Named IOs

You can set your own named IOs to the container.

class SmileLog < Cli::Command
  on_initialize do |cmd|
    cmd.io[:smiles] = File.open("/path/to/smiles", "w+")   
  end

  def run
    io[:smiles].puts ":)"
  end
end

Clone this wiki locally