Question

I have this code sample:

#!/usr/bin/env ruby
require_relative File.expand_path('../../lib/argosnap', __FILE__)
require 'optparse'

options = {}

opt_parser = OptionParser.new do |opt|
  opt.banner = "argosnap #{Argosnap::VERSION} ( http://github/atmosx/argosnap )\nUsage: argosnap [OPTIONS]"
  opt.separator  ""
  opt.separator  "     version: dislay version"
  opt.separator  "     install: installs 'config.yml' and launchd script"
  opt.separator  "     balance: check picodollars"
  opt.separator  ""

  opt.on("-v","--version","display version") do |version|
    options[:version] = version
  end

  opt.on("-c","--config [TYPE]", String, "install configuration files") do |config|
    options[:config] = config
  end

  opt.on("-b","--balance","executes 'argosnap' and displayes notifications") do |balance|
    options[:balance] = balance
  end

  opt.on("-h","--help","help") do
    puts opt_parser
  end
end

begin
  opt_parser.parse!
rescue OptionParser::InvalidOption => e
  puts "No such option! Type 'argosnap -h' for help!"
  exit
end

case ARGV[0]
when "version"
  puts Argosnap::VERSION
when "config"
  Argosnap::Install.new.config
when "balance"
  b = Argosnap::Fetch.new.balance
  puts "Current balance (picodollars): #{b}"
else
  puts "Type: 'argosnap -h' for help!"
end

My problem is that options hash is empty. It's like if it doesn't accept the options[:var] = var defined inside the OptParser class. I'd like to use -v and --version in my program to make it more unix-like.

I'm using ruby-2.0.

UPDATE: The way it is the code works I've tried changing when "version" with when '-v' or when options[:version] which seemed the best approach to me, but nothing worked.

Was it helpful?

Solution

when you write case ARGV[0] you are totally ignoring the opt_parser...
ARGV[0] is the first word in the command line. The whole point of opt_parser is that you don't look at ARGV:

if options[:version]
  puts Argosnap::VERSION
elsif options[:config]
  Argosnap::Install.new.config
elsif options[:balance]
  b = Argosnap::Fetch.new.balance
  puts "Current balance (picodollars): #{b}"
else
  puts "Type: 'argosnap -h' for help!"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top