Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable.
This commit is contained in:
parent
7564d98929
commit
676b0c8764
@ -1,3 +1,8 @@
|
||||
*Edge*
|
||||
|
||||
* Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable. [Jeremy Kemper]
|
||||
|
||||
|
||||
*2.3.0 [RC1] (February 1st, 2009)*
|
||||
|
||||
* TimeWithZone#xmlschema accepts optional fraction_digits argument [#1725 state:resolved] [Nicholas Dainty]
|
||||
|
@ -3,6 +3,7 @@
|
||||
require 'active_support/core_ext/array/extract_options'
|
||||
require 'active_support/core_ext/array/grouping'
|
||||
require 'active_support/core_ext/array/random_access'
|
||||
require 'active_support/core_ext/array/wrapper'
|
||||
|
||||
class Array #:nodoc:
|
||||
include ActiveSupport::CoreExtensions::Array::Access
|
||||
@ -10,4 +11,5 @@ class Array #:nodoc:
|
||||
include ActiveSupport::CoreExtensions::Array::ExtractOptions
|
||||
include ActiveSupport::CoreExtensions::Array::Grouping
|
||||
include ActiveSupport::CoreExtensions::Array::RandomAccess
|
||||
extend ActiveSupport::CoreExtensions::Array::Wrapper
|
||||
end
|
||||
|
19
activesupport/lib/active_support/core_ext/array/wrapper.rb
Normal file
19
activesupport/lib/active_support/core_ext/array/wrapper.rb
Normal file
@ -0,0 +1,19 @@
|
||||
module ActiveSupport #:nodoc:
|
||||
module CoreExtensions #:nodoc:
|
||||
module Array #:nodoc:
|
||||
module Wrapper
|
||||
# Wraps the object in an Array unless it's an Array.
|
||||
def wrap(object)
|
||||
case object
|
||||
when nil
|
||||
[]
|
||||
when self
|
||||
object
|
||||
else
|
||||
[object]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
@ -302,3 +302,27 @@ def test_random_element_from_array
|
||||
assert_equal 2, [1, 2, 3].rand
|
||||
end
|
||||
end
|
||||
|
||||
class ArrayWrapperTests < Test::Unit::TestCase
|
||||
def test_array
|
||||
ary = %w(foo bar)
|
||||
assert_same ary, Array.wrap(ary)
|
||||
end
|
||||
|
||||
def test_nil
|
||||
assert_equal [], Array.wrap(nil)
|
||||
end
|
||||
|
||||
def test_object
|
||||
o = Object.new
|
||||
assert_equal [o], Array.wrap(o)
|
||||
end
|
||||
|
||||
def test_string
|
||||
assert_equal ["foo"], Array.wrap("foo")
|
||||
end
|
||||
|
||||
def test_string_with_newline
|
||||
assert_equal ["foo\nbar"], Array.wrap("foo\nbar")
|
||||
end
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user