How do I make a Ruby script using Trollop for comm

2019-02-15 10:06发布

I've recently started using Trollop, a clean and elegant command line option parser for all my small Ruby-based command line hacks. I found it was really easy to use, but getting started was difficult: despite good online documentation, there wasn't anything that showed how to incorporate Trollop into a complete script.

Q: How can I incorporate Trollop into my Ruby command-line program?

1条回答
Root(大扎)
2楼-- · 2019-02-15 10:44

A: Here is a self-contained example.

The business with if __FILE__ == $0 isn't specific to Trollop; that just means "run the following code if this file is executed as a script". This technique allows you use the file as a library module, separating the business logic from the command line parsing.

#!/usr/bin/env ruby
# 
# This is a near-minimal ruby script to demonstrate trollop, a simple
# and elegant command-line parsing package.  To run, copy this file to
# 'trollop_demo.rb' and make it executable by
#   $ chmod +x trollop_demo.rb
# Then run it via:
#   $ ./trollop_demo.rb <your args here>
# For more info on Trollop, see http://trollop.rubyforge.org/
require 'trollop'

# A trivial program...
def main_method(filename, options)
  puts("filename = #{filename}, options = #{options}")
end

# Execute this part when the file is run as a script
if __FILE__ == $0
  opts = Trollop::options do
    version "#{$0} Version 3.14159 (C) 2041 Spacely Sprockets, Inc."
    banner <<-EOS
#{$0} is a command-line program to demonstrate trollop
Usage:
        #{$0} [options] <filename>
where [options] are zero or more of:
EOS
    opt :verbose, "Print extra information."
    opt :dry_run, "Don't actually do anything.", :short => "-n"
  end
  filename = ARGV.shift
  if (filename.nil?) || (!File.exist?(filename))
    Trollop::die "filename must be given and name an existing file"
  else
    main_method(filename, opts)
  end
end

With just that bit of code, you can now try all these things:

$ ./trollop_demo.rb 
$ ./trollop_demo.rb a_file_that_doesn't_exist
$ ./trollop_demo.rb --version
$ ./trollop_demo.rb --help
$ ./trollop_demo.rb trollop_demo.rb
$ ./trollop_demo.rb --dry-run trollop_demo.rb
$ ./trollop_demo.rb --no-dry-run trollop_demo.rb
$ ./trollop_demo.rb --verbose trollop_demo.rb
$ ./trollop_demo.rb -v trollop_demo.rb

For more information, see http://trollop.rubyforge.org/

查看更多
登录 后发表回答