Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created November 2, 2011 18:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leejarvis/1334515 to your computer and use it in GitHub Desktop.
Save leejarvis/1334515 to your computer and use it in GitHub Desktop.
require 'slop'
optspec = <<-SPEC
ruby foo.rb [options]
---
n,name= Set your name
a,age= Set your age
v,verbose Enable verbose mode
debug Enable debug mode
SPEC
opts = Slop.optspec(optspec)
opts.parse
puts opts #=>
# ruby foo.rb [options]
#
# options:
#
# -n, --name Set your name
# -a, --age Set your age
# -v, --verbose Enable verbose mode
# --debug Enable debug mode
# ruby foo.rb --name "Lee Jarvis" --debug -a 102
opts.debug? #=> true
opts[:name] #=> "Lee Jarvis"
opts[:age] #=> 102
opts.verbose? #=> false
@ilkka
Copy link

ilkka commented Nov 8, 2011

Am I missing something or does this method leave the flags in ARGV? I was just upgrading a script from an older slop and there I was relying on the fact that they got scrubbed out of ARGV so I could just iterate that for e.g. files I needed to process.

@leejarvis
Copy link
Author

The parse method does not strip flags out, you want the parse! method for that.

@ilkka
Copy link

ilkka commented Nov 9, 2011

Great, thanks!

@alialshahib
Copy link

How can I add a required option which gives a error to the user when the option is not given as an argument

@leejarvis
Copy link
Author

@alialshahib I found that to be a unique use case, because --options are usually just that, optional. You can handle it pretty easily yourself, though:

raise "You didn't supply the --omg option!" unless opts.omg?

If you want something to do this built into Slop, please open an issue with a suggestion :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment