summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLee Jarvis <ljjarvis@gmail.com>2014-11-19 13:00:35 +0000
committerLee Jarvis <ljjarvis@gmail.com>2014-11-19 13:00:35 +0000
commite3901588e3e767ffd6a08e32b535d15c5032351a (patch)
treea12273434e679ee7e5d4917e515aa48ce069c8e3
parentc811bc2e28b2326b924c69abe2e4729508f482b5 (diff)
downloadslop-e3901588e3e767ffd6a08e32b535d15c5032351a.tar.gz
Add custom "finish" method for options
-rw-r--r--lib/slop/option.rb9
-rw-r--r--lib/slop/parser.rb4
-rw-r--r--lib/slop/result.rb8
-rw-r--r--test/result_test.rb17
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"]