diff options
author | Lee Jarvis <ljjarvis@gmail.com> | 2014-11-19 13:00:35 +0000 |
---|---|---|
committer | Lee Jarvis <ljjarvis@gmail.com> | 2014-11-19 13:00:35 +0000 |
commit | e3901588e3e767ffd6a08e32b535d15c5032351a (patch) | |
tree | a12273434e679ee7e5d4917e515aa48ce069c8e3 /lib | |
parent | c811bc2e28b2326b924c69abe2e4729508f482b5 (diff) | |
download | slop-e3901588e3e767ffd6a08e32b535d15c5032351a.tar.gz |
Add custom "finish" method for options
Diffstat (limited to 'lib')
-rw-r--r-- | lib/slop/option.rb | 9 | ||||
-rw-r--r-- | lib/slop/parser.rb | 4 | ||||
-rw-r--r-- | lib/slop/result.rb | 8 |
3 files changed, 19 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] }] |