summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLee Jarvis <lee@jarvis.co>2011-04-16 14:09:36 +0100
committerLee Jarvis <lee@jarvis.co>2011-04-16 14:09:36 +0100
commit7bf3c40fc8387bd936e3ef71cba9b5e28ceb6adc (patch)
treec3f682172d6a8db2b09f65fe7a68d24c6e578c85
parentc89fb97be7af2e37140d272cf9bdc6d4e065d8eb (diff)
downloadslop-7bf3c40fc8387bd936e3ef71cba9b5e28ceb6adc.tar.gz
add Slop.split method
-rw-r--r--lib/slop.rb14
-rw-r--r--test/slop_test.rb11
2 files changed, 25 insertions, 0 deletions
diff --git a/lib/slop.rb b/lib/slop.rb
index ae95559..1fc41f8 100644
--- a/lib/slop.rb
+++ b/lib/slop.rb
@@ -18,6 +18,20 @@ class Slop
# @return [String] The current version string
VERSION = '1.4.1'
+ # Split a string into easily parsable segments for sending to Slop
+ # @param [String] string The string to be parsed
+ # @example
+ # Slop.split("foo 'bar baz' stuff") #=> ["foo", "bar baz", "stuff"]
+ # @return [Array]
+ def self.split(string)
+ return unless string && string.respond_to?(:to_str)
+ strings = []
+ string.scan(/(['"]([^'"]+)['"]|\S+)/) do |s|
+ strings << (s[1] || s[0])
+ end
+ strings
+ end
+
# Parses the items from a CLI format into a friendly object.
#
# @param [Array] items Items to parse into options.
diff --git a/test/slop_test.rb b/test/slop_test.rb
index 2ada9a9..ec83495 100644
--- a/test/slop_test.rb
+++ b/test/slop_test.rb
@@ -13,6 +13,17 @@ class SlopTest < TestCase
ARGV.replace old_argv
end
+ test 'Slop.split' do
+ assert_equal ['foo', 'bar'], Slop.split("foo bar")
+ assert_equal ['foo bar', 'baz'], Slop.split("'foo bar' baz")
+ assert_equal ['foo bar', 'baz'], Slop.split(' "foo bar" baz ')
+ assert_equal [' foo bar ', 'baz'], Slop.split('" foo bar " baz')
+ assert_equal ['foo,', 'bar'], Slop.split("foo, bar")
+ assert_equal [], Slop.split("")
+ assert_nil Slop.split []
+ assert_nil Slop.split :foo
+ end
+
test 'includes Enumerable' do
assert Slop.included_modules.include?(Enumerable)
end