diff options
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/CHANGELOG | 2 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/inclusion.rb | 20 | ||||
-rw-r--r-- | activesupport/test/core_ext/object/inclusion_test.rb | 52 |
3 files changed, 74 insertions, 0 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 373236ce9a..8e7e2d188b 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *Rails 3.1.0 (unreleased)* +* Add Object#in? to test if an object is included in another object, and Object#either? to test if an object is included in a list of objects which will be passed as arguments. [Prem Sichanugrist, Brian Morearty, John Reitano] + * LocalCache strategy is now a real middleware class, not an anonymous class posing for pictures. diff --git a/activesupport/lib/active_support/core_ext/object/inclusion.rb b/activesupport/lib/active_support/core_ext/object/inclusion.rb new file mode 100644 index 0000000000..79e9fd6c88 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/inclusion.rb @@ -0,0 +1,20 @@ +class Object + # Returns true if this object is included in the argument. Argument must be + # any object which respond to +#include?+. Usage: + # + # characters = ["Konata", "Kagami", "Tsukasa"] + # "Konata".in?(characters) # => true + # + def in?(another_object) + another_object.include?(self) + end + + # Returns true if this object is included in the argument list. Usage: + # + # username = "sikachu" + # username.either?("josevalim", "dhh", "wycats") # => false + # + def either?(*objects) + objects.include?(self) + end +end diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb new file mode 100644 index 0000000000..b4207c20ea --- /dev/null +++ b/activesupport/test/core_ext/object/inclusion_test.rb @@ -0,0 +1,52 @@ +require 'abstract_unit' +require 'active_support/core_ext/object/inclusion' + +class InTest < Test::Unit::TestCase + def test_in_array + assert 1.in?([1,2]) + assert !3.in?([1,2]) + end + + def test_in_hash + h = { "a" => 100, "b" => 200 } + assert "a".in?(h) + assert !"z".in?(h) + end + + def test_in_string + assert "lo".in?("hello") + assert !"ol".in?("hello") + assert ?h.in?("hello") + end + + def test_in_range + assert 25.in?(1..50) + assert !75.in?(1..50) + end + + def test_in_set + s = Set.new([1,2]) + assert 1.in?(s) + assert !3.in?(s) + end + + def test_either + assert 1.either?(1,2,3) + assert !5.either?(1,2,3) + assert [1,2,3].either?([1,2,3], 2, [3,4,5]) + end + + module A + end + class B + include A + end + class C < B + end + + def test_in_module + assert A.in?(B) + assert A.in?(C) + assert !A.in?(A) + end +end |