summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLee Jarvis <lee@jarvis.co>2012-01-23 14:19:44 +0000
committerLee Jarvis <lee@jarvis.co>2012-01-23 14:19:44 +0000
commit44cd850b6f8cce244b9f55537196baf0dc9c2f7a (patch)
tree07278a9e90bb78f1c378abbe9904b8d7301d603b
parenteecbddbb12c65eb672bf14f2510a73e1aae37d5b (diff)
downloadslop-44cd850b6f8cce244b9f55537196baf0dc9c2f7a.tar.gz
value_to_range return a range even if the value looks like an
integer (#48) value_to_range raises InvalidArgumentError if the value does not look like a type of range and :strict mode is enabled
-rw-r--r--lib/slop/option.rb18
-rw-r--r--test/option_test.rb4
2 files changed, 15 insertions, 7 deletions
diff --git a/lib/slop/option.rb b/lib/slop/option.rb
index 01c44bb..ffd8651 100644
--- a/lib/slop/option.rb
+++ b/lib/slop/option.rb
@@ -129,19 +129,23 @@ class Slop
private
- # Convert an object to a Range if possible. If this method is passed
- # what does *not* look like a Range, but looks like an Integer of some
- # sort, it will call #to_i on the Object and return the Integer
- # representation.
+ # Convert an object to a Range if possible.
#
# value - The Object we want to convert to a range.
#
# Returns the Range value if one could be found, else the original object.
def value_to_range(value)
- if value.to_s =~ /\A(?:\-?\d+|(-?\d+?)(\.\.\.?|-|,)(-?\d+))\z/
- $1 ? Range.new($1.to_i, $3.to_i, $2 == '...') : value.to_i
+ case value.to_s
+ when /\A(\-?\d+)\z/
+ Range.new($1.to_i, $1.to_i)
+ when /\A(-?\d+?)(\.\.\.?|-|,)(-?\d+)\z/
+ Range.new($1.to_i, $3.to_i, $2 == '...')
else
- value
+ if @slop.config[:strict]
+ raise InvalidArgumentError, "#{value} could not be coerced into Range"
+ else
+ value
+ end
end
end
diff --git a/test/option_test.rb b/test/option_test.rb
index eff283b..0daaa0c 100644
--- a/test/option_test.rb
+++ b/test/option_test.rb
@@ -66,6 +66,10 @@ class OptionTest < TestCase
assert_equal (1...10), option_value(%w/-r 1...10/, :r=, :as => Range)
assert_equal (-1..10), option_value(%w/-r -1..10/, :r=, :as => Range)
assert_equal (1..-10), option_value(%w/-r 1..-10/, :r=, :as => Range)
+ assert_equal (1..1), option_value(%w/-r 1/, :r=, :as => Range)
+
+ opts = Slop.new(:strict => true) { on :r=, :as => Range }
+ assert_raises(Slop::InvalidArgumentError) { opts.parse %w/-r abc/ }
end
test "array type cast" do