summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorLee Jarvis <ljjarvis@gmail.com>2014-12-19 16:08:04 +0000
committerLee Jarvis <ljjarvis@gmail.com>2014-12-19 16:17:19 +0000
commit7cee65ee47c365799bfe0f03217036c1dc0787b2 (patch)
tree7009bb91911333393d24c4dc42838a0ca6061069 /lib
parent6c509658f8052f1ef9dba8ed5db2207e6375665e (diff)
downloadslop-7cee65ee47c365799bfe0f03217036c1dc0787b2.tar.gz
Add result/parser `arguments` method
Diffstat (limited to 'lib')
-rw-r--r--lib/slop/parser.rb16
-rw-r--r--lib/slop/result.rb18
2 files changed, 32 insertions, 2 deletions
diff --git a/lib/slop/parser.rb b/lib/slop/parser.rb
index a46858e..50b031c 100644
--- a/lib/slop/parser.rb
+++ b/lib/slop/parser.rb
@@ -7,6 +7,9 @@ module Slop
# A Hash of configuration options.
attr_reader :config
+ # Returns an Array of String arguments that were not parsed.
+ attr_reader :arguments
+
def initialize(options, **config)
@options = options
@config = config
@@ -16,6 +19,7 @@ module Slop
# Reset the parser, useful to use the same instance to parse a second
# time without duplicating state.
def reset
+ @arguments = []
@options.each(&:reset)
self
end
@@ -35,6 +39,8 @@ module Slop
# otherwise it'll only be used as an argument.
pairs << [strings.last, nil]
+ @arguments = strings.dup
+
pairs.each do |flag, arg|
# ignore everything after '--', flag or not
break if !flag || flag == '--'
@@ -44,7 +50,12 @@ module Slop
flag, arg = flag.split("=")
end
- try_process(flag, arg)
+ if opt = try_process(flag, arg)
+ # since the option was parsed, we remove it from our
+ # arguments (plus the arg if necessary)
+ arguments.delete(flag)
+ arguments.delete(arg) if opt.expects_argument?
+ end
end
Result.new(self).tap do |result|
@@ -64,9 +75,10 @@ module Slop
private
- # We've found an option, process it
+ # We've found an option, process and return it
def process(option, arg)
option.ensure_call(arg)
+ option
end
# Try and find an option to process
diff --git a/lib/slop/result.rb b/lib/slop/result.rb
index aaa4efe..8cdfa12 100644
--- a/lib/slop/result.rb
+++ b/lib/slop/result.rb
@@ -40,14 +40,32 @@ module Slop
name.to_s.end_with?("?") || super
end
+ # Returns an Array of Option instances that were used.
def used_options
parser.used_options
end
+ # Returns an Array of Option instances that were not used.
def unused_options
parser.unused_options
end
+ # Example:
+ #
+ # opts = Slop.parse do |o|
+ # o.string '--host'
+ # o.int '-p'
+ # end
+ #
+ # # ruby run.rb connect --host 123 helo
+ # opts.arguments #=> ["connect", "helo"]
+ #
+ # Returns an Array of String arguments that were not parsed.
+ def arguments
+ parser.arguments
+ end
+ alias args arguments
+
# Returns a hash with option key => value.
def to_hash
Hash[options.reject(&:null?).map { |o| [o.key, o.value] }]