Some projects I've seen implement their command line tools as Command objects (for example: Rubygems and my escape stone). ARGV, , . . , , , STDOUT/STDIN. , , / . , , , . Command.
:
require 'pathname'
class MyCommand
attr_accessor :input, :output, :error, :working_dir
def initialize(options = {})
@input = options[:input] ? options[:input] : STDIN
@output = options[:output] ? options[:output] : STDOUT
@error = options[:error] ? options[:error] : STDERR
@working_dir = options[:working_dir] ? Pathname.new(options[:working_dir]) : Pathname.pwd
end
def puts(output = nil)
@output.puts(output)
end
def execute(arguments = ARGV)
Dir.chdir(working_dir) do
if arguments[0] == '--readfile'
posts_dir = Pathname.new('posts')
my_file = posts_dir + 'myfile'
puts my_file.read
end
end
end
end
if __FILE__ == $PROGRAM_NAME
MyCommand.new.execute
end
:
require 'pathname'
require 'tmpdir'
require 'stringio'
def setup
@working_dir = Pathname.new(Dir.mktmpdir('mycommand'))
@output = StringIO.new
@error = StringIO.new
@command = MyCommand.new(:working_dir => @working_dir, :output => @output, :error => @error)
end
def test_some_stuff
@command.execute(['--readfile'])
end
def teardown
@working_dir.rmtree
end
( Pathname, - API- Ruby StringIO, STDOUT, -, )
acutal @working_dir :
path = @working_dir + 'posts' + 'myfile'
path.exist?
path.file?
path.directory?
path.read == "abc\n"