Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Insure that Enumerable#index_by, group_by, ... return Enumerators

  • Loading branch information...
commit 816abecf90167c4df7d2117188bfa9d19b752696 1 parent c785038
@marcandre marcandre authored
View
3  activesupport/lib/active_support/core_ext/enumerable.rb
@@ -20,6 +20,7 @@ module Enumerable
# "2006-02-24 -> Transcript, Transcript"
# "2006-02-23 -> Transcript"
def group_by
+ return to_enum :group_by unless block_given?
assoc = ActiveSupport::OrderedHash.new
each do |element|
@@ -76,6 +77,7 @@ def sum(identity = 0, &block)
# (1..5).each_with_object(1) { |value, memo| memo *= value } # => 1
#
def each_with_object(memo, &block)
+ return to_enum :each_with_object, memo unless block_given?
each do |element|
block.call(element, memo)
end
@@ -90,6 +92,7 @@ def each_with_object(memo, &block)
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
#
def index_by
+ return to_enum :index_by unless block_given?
Hash[map { |elem| [yield(elem), elem] }]
end
View
13 activesupport/test/core_ext/enumerable_test.rb
@@ -8,6 +8,8 @@ def +(p) self.class.new(price + p.price) end
end
class EnumerableTests < Test::Unit::TestCase
+ Enumerator = [].each.class
+
class GenericEnumerable
include Enumerable
def initialize(values = [1, 2, 3])
@@ -28,7 +30,8 @@ def test_group_by
people << p
end
- grouped = GenericEnumerable.new(objects).group_by { |object| object.name }
+ enum = GenericEnumerable.new(objects)
+ grouped = enum.group_by { |object| object.name }
grouped.each do |name, group|
assert group.all? { |person| person.name == name }
@@ -36,6 +39,8 @@ def test_group_by
assert_equal objects.uniq.map(&:name), grouped.keys
assert({}.merge(grouped), "Could not convert ActiveSupport::OrderedHash into Hash")
+ assert_equal Enumerator, enum.group_by.class
+ assert_equal grouped, enum.group_by.each(&:name)
end
def test_sums
@@ -85,12 +90,18 @@ def test_each_with_object
enum = GenericEnumerable.new(%w(foo bar))
result = enum.each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
assert_equal({'foo' => 'FOO', 'bar' => 'BAR'}, result)
+ assert_equal Enumerator, enum.each_with_object({}).class
+ result2 = enum.each_with_object({}).each{|str, hsh| hsh[str] = str.upcase}
+ assert_equal result, result2
end
def test_index_by
payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
payments.index_by { |p| p.price })
+ assert_equal Enumerator, payments.index_by.class
+ assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
+ payments.index_by.each { |p| p.price })
end
def test_many
Please sign in to comment.
Something went wrong with that request. Please try again.