summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLee Jarvis <lee@jarvis.co>2012-07-31 18:40:44 +0100
committerLee Jarvis <lee@jarvis.co>2012-07-31 18:40:44 +0100
commitccadb9da05f9a3eb0e38c07229869288ed056750 (patch)
tree83ff858eebb3d1eb03f8df61c46afb3fcaf82cc6
parentc91dfb3f66e877f579ed972376080f7abadd9282 (diff)
downloadslop-ccadb9da05f9a3eb0e38c07229869288ed056750.tar.gz
add the ability to concat list arguments together as a single value
closes #71
-rw-r--r--lib/slop/option.rb19
-rw-r--r--test/option_test.rb1
2 files changed, 18 insertions, 2 deletions
diff --git a/lib/slop/option.rb b/lib/slop/option.rb
index 664bb98..3ad4f6c 100644
--- a/lib/slop/option.rb
+++ b/lib/slop/option.rb
@@ -19,7 +19,6 @@ class Slop
attr_reader :short, :long, :description, :config, :types
attr_accessor :count
- attr_writer :value
# Incapsulate internal option information, mainly used to store
# option specific configuration data, most of the meat of this
@@ -45,7 +44,6 @@ class Slop
:symbol => proc { |v| v.to_sym },
:integer => proc { |v| value_to_integer(v) },
:float => proc { |v| value_to_float(v) },
- :array => proc { |v| v.split(@config[:delimiter], @config[:limit]) },
:range => proc { |v| value_to_range(v) },
:count => proc { |v| @count }
}
@@ -81,6 +79,23 @@ class Slop
@callback.call(*objects) if @callback.respond_to?(:call)
end
+ # Set the new argument value for this option.
+ #
+ # We use this setter method to handle concatenating lists. That is,
+ # when an array type is specified and used more than once, values from
+ # both options will be grouped together and flattened into a single array.
+ def value=(new_value)
+ if config[:as].to_s.downcase == 'array'
+ @value ||= []
+
+ if new_value.respond_to?(:split)
+ @value.concat new_value.split(config[:delimiter], config[:limit])
+ end
+ else
+ @value = new_value
+ end
+ end
+
# Fetch the argument value for this option.
#
# Returns the Object once any type conversions have taken place.
diff --git a/test/option_test.rb b/test/option_test.rb
index 0a82aed..acd625f 100644
--- a/test/option_test.rb
+++ b/test/option_test.rb
@@ -86,6 +86,7 @@ class OptionTest < TestCase
test "array type cast" do
assert_equal %w/lee john bill/, option_value(%w/-p lee,john,bill/, :p=, :as => Array)
+ assert_equal %w/lee john bill jeff jill/, option_value(%w/-p lee,john,bill -p jeff,jill/, :p=, :as => Array)
assert_equal %w/lee john bill/, option_value(%w/-p lee:john:bill/, :p=, :as => Array, :delimiter => ':')
assert_equal %w/lee john,bill/, option_value(%w/-p lee,john,bill/, :p=, :as => Array, :limit => 2)
assert_equal %w/lee john:bill/, option_value(%w/-p lee:john:bill/, :p=, :as => Array, :limit => 2, :delimiter => ':')