diff options
-rw-r--r-- | lib/slop.rb | 19 | ||||
-rw-r--r-- | test/slop_test.rb | 8 |
2 files changed, 27 insertions, 0 deletions
diff --git a/lib/slop.rb b/lib/slop.rb index ef2ffa5..87ad448 100644 --- a/lib/slop.rb +++ b/lib/slop.rb @@ -65,6 +65,7 @@ class Slop @strict = sloptions[:strict] @invalid_options = [] @multiple_switches = sloptions[:multiple_switches] + @on_empty = sloptions[:on_empty] if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) @@ -155,6 +156,19 @@ class Slop alias :opt :option alias :on :option + # Add an object to be called when Slop has no values to parse + # + # @param [Object, nil] proc The object (which can be anything + # responding to :call) + # @example + # Slop.parse do + # on_empty { puts 'No argument given!' } + # end + def on_empty(obj=nil, &block) + @on_empty ||= (obj || block) + end + alias :on_empty= :on_empty + # Returns the parsed list into a option/value hash. # # @example @@ -209,6 +223,11 @@ class Slop end def parse_items(items, delete=false, &block) + if items.empty? && @on_empty.respond_to?(:call) + @on_empty.call self + return + end + trash = [] items.each do |item| diff --git a/test/slop_test.rb b/test/slop_test.rb index 57f1aa8..2ada9a9 100644 --- a/test/slop_test.rb +++ b/test/slop_test.rb @@ -44,6 +44,14 @@ class SlopTest < TestCase end end + test 'callback when option array is empty' do + item1 = item2 = nil + Slop.new { on_empty { item1 = 'foo' } }.parse + + assert_equal 'foo', item1 + assert_nil item2 + end + test 'multiple switches with the :multiple_switches flag' do slop = Slop.new :multiple_switches => true, :strict => true %w/a b c/.each { |f| slop.on f } |