From aa6a1094de3146df17721df0752274f4ddd04ea9 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Mon, 17 May 2010 01:49:39 +0430 Subject: [PATCH] Deprecate Array#rand in favor of Array#random_element --- .../active_support/core_ext/array/random_access.rb | 12 +++++++++++- activesupport/test/core_ext/array_ext_test.rb | 10 +++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb index 54d17cb..2ec1144 100644 --- a/activesupport/lib/active_support/core_ext/array/random_access.rb +++ b/activesupport/lib/active_support/core_ext/array/random_access.rb @@ -2,8 +2,18 @@ module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Array #:nodoc: module RandomAccess + # This method is deprecated because it masks Kernel#rand within the Array class itself, + # which may be used by a 3rd party library extending Array in turn. See + # + # https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4555 + # + def rand # :nodoc: + ActiveSupport::Deprecation.warn 'Array#rand is deprecated and will be removed in Rails 3. Use "random_element" instead', caller + random_element + end + # Returns a random element from the array. - def rand + def random_element self[Kernel.rand(length)] end end diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index f354ade..b891531 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -325,13 +325,17 @@ end class ArrayExtRandomTests < Test::Unit::TestCase def test_random_element_from_array - assert_nil [].rand + assert_nil [].random_element Kernel.expects(:rand).with(1).returns(0) - assert_equal 'x', ['x'].rand + assert_equal 'x', ['x'].random_element Kernel.expects(:rand).with(3).returns(1) - assert_equal 2, [1, 2, 3].rand + assert_equal 2, [1, 2, 3].random_element + end + + def test_deprecated_rand_on_array + assert_deprecated { [].rand } end end -- 1.6.5.2