Question

Does Ruby support POD documentation or any alternative?

I am interesting in it, because I don't know how to provide some simple '-h' option help. Maybe I am wrong here, please, give me good examples.

My example:

$ ruby rubyScript.rb -h
This message is shown if you pass parameter -h.

And my implementation of this will be:

require 'optparse'

def HelpMessage()
  puts <<-__HELP__
  This message is shown if you pass parameter -h.
  __HELP__
end
OptionParser.new do |opts|
  opts.banner = "Usage: rubyScript.rb [options]"
  opts.on('-h', '--help', 'Help option') { HelpMessage(); exit()}
end.parse!

This is a bit ugly code, I think, but I don't know another way to create simple help

Was it helpful?

Solution

OptionParser makes it a lot easier than you think.

Save this to a file:

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: rubyScript.rb [options]"

  opts.on('-i', '--input FILE', 'Input file') { |o| options[:input] = o }
  opts.on('-o', '--output FILE', 'Output file') { |o| options[:output] = o }

  options[:help] = opts.help
end.parse!

puts options[:help]

Running that with no options will output:

Usage: rubyScript.rb [options]
    -i, --input FILE                 Input file
    -o, --output FILE                Output file

which means you can programmatically display the help any time you need to.

Take out the line:

puts options[:help]

and running it again with a -h option displays the same thing, showing that OptionParser automatically provides a -h and --help option unless you override those.

Does Ruby support POD documentation or any alternative?

Yes, but that wouldn't help you in this case unless you expect a user to actually take the time to read your documentation before using your application. Ruby's RDoc can nicely parse your code and extract all sorts of programmer's information for the script. See the RDoc example page's "example" section for a working... uh... example. RDoc is included with Ruby, unless you're using a yum/apt-get installation, which, in that case, you might need to install the RDoc/ri package. ri is Ruby's built-in documentation, which can display help for your code at the command-line and its source files are created by rdoc.

OTHER TIPS

Put this line around the top of your code:

(puts "This message is shown if you pass parameter -h."; exit) if ARGV.first == "-h"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top