replace usage of `returning` with `each_with_object`

`each_with_object` is a Ruby 1.9 method, here re-implemented in core_ext.rb
in case it's missing (for older Ruby versions). Using `returning` is bad in
combination with Ruby on Rails because each usage of the method will emit
a Rails deprecation warning. This might be considered an Active Support bug,
but it's better to avoid using `returning` altogether and use `tap` from
Ruby 1.8.7, also re-implemented here in case it's missing.

Since existing usages or `returning` were better suited for `each_with_object`
than `tap`, they were rewritten using the former instead.
This commit is contained in:
Mislav Marohnić 2010-09-04 21:14:46 +08:00 committed by Kyle Banker
parent b9de2eaa5c
commit 56f37e49b6
3 changed files with 18 additions and 9 deletions

View File

@ -277,8 +277,8 @@ module Mongo
# @return [Hash]
def database_info
doc = self['admin'].command({:listDatabases => 1})
returning({}) do |info|
doc['databases'].each { |db| info[db['name']] = db['sizeOnDisk'].to_i }
doc['databases'].each_with_object({}) do |db, info|
info[db['name']] = db['sizeOnDisk'].to_i
end
end

View File

@ -321,9 +321,7 @@ module Mongo
{fields => 1}
when Array
return nil if fields.length.zero?
returning({}) do |hash|
fields.each { |field| hash[field] = 1 }
end
fields.each_with_object({}) { |field, hash| hash[field] = 1 }
when Hash
return fields
end

View File

@ -20,10 +20,21 @@
class Object
#:nodoc:
def returning(value)
yield value
value
end
def tap
yield self
self
end unless respond_to? :tap
end
#:nodoc:
module Enumerable
#:nodoc:
def each_with_object(memo)
each { |element| yield(element, memo) }
memo
end unless [].respond_to?(:each_with_object)
end