diff options
-rw-r--r-- | lib/slop/option.rb | 9 | ||||
-rw-r--r-- | lib/slop/parser.rb | 4 | ||||
-rw-r--r-- | lib/slop/result.rb | 8 | ||||
-rw-r--r-- | test/result_test.rb | 17 |
4 files changed, 36 insertions, 2 deletions
diff --git a/lib/slop/option.rb b/lib/slop/option.rb index a624110..9c11080 100644 --- a/lib/slop/option.rb +++ b/lib/slop/option.rb @@ -1,6 +1,7 @@ module Slop class Option attr_reader :flags, :desc, :config, :count + attr_writer :value def initialize(flags, desc, **config) @flags = flags @@ -24,11 +25,17 @@ module Slop @value = call(value) end - def call(value) + def call(_value) raise NotImplementedError, "you must override the `call' method for option #{self.class}" end + # By default this method does nothing. It's called when all options + # have been parsed and allows you to mutate the `@value` attribute + # according to other options. + def finish(_result) + end + def value @value || config[:default] end diff --git a/lib/slop/parser.rb b/lib/slop/parser.rb index 0ef4931..ef31ee1 100644 --- a/lib/slop/parser.rb +++ b/lib/slop/parser.rb @@ -30,7 +30,9 @@ module Slop end end - Result.new(self) + Result.new(self).tap do |result| + used_options.each { |o| o.finish(result) } + end end def unused_options diff --git a/lib/slop/result.rb b/lib/slop/result.rb index 5dd5213..0d0a3ab 100644 --- a/lib/slop/result.rb +++ b/lib/slop/result.rb @@ -27,6 +27,14 @@ module Slop end end + def used_options + parser.used_options + end + + def unused_options + parser.unused_options + end + # Returns a hash with option key => value. def to_hash Hash[options.map { |o| [o.key, o.value] }] diff --git a/test/result_test.rb b/test/result_test.rb index 68fd83f..cfa66d2 100644 --- a/test/result_test.rb +++ b/test/result_test.rb @@ -1,5 +1,15 @@ require 'test_helper' +module Slop + class ReverseEverythingOption < BoolOption + def finish(result) + result.used_options.grep(Slop::StringOption).each do |opt| + opt.value = opt.value.reverse + end + end + end +end + describe Slop::Result do before do @options = Slop::Options.new @@ -22,6 +32,13 @@ describe Slop::Result do assert_equal "bar", @result[:foo] end + it "handles custom finishing" do + @options.string "--foo" + @options.reverse_everything "-r" + @result.parser.reset.parse %w(-r --name lee --foo bar) + assert_equal %w(eel rab), @result.to_hash.values_at(:name, :foo) + end + describe "#[]" do it "returns an options value" do assert_equal "lee", @result["name"] |