提交 c046e609 编写于 作者: P Parker Selbert

Return a hash rather than array from fetch_multi

The current implementation of `fetch_multi` returns an array and has no
means to easily backtrack which names yielded which results. By changing
the return value to a Hash we retain the name information. Hash#values
can be used on the response if only the values are needed.
上级 7c92e0bb
* Change the signature of `fetch_multi` to return a hash rather than an
array. This makes it consistent with the output of `read_multi`.
*Parker Selbert*
* Introduce `Concern#class_methods` as a sleek alternative to clunky
`module ClassMethods`. Add `Kernel#concern` to define at the toplevel
without chunky `module Foo; extend ActiveSupport::Concern` boilerplate.
......
......@@ -357,20 +357,19 @@ def read_multi(*names)
#
# Options are passed to the underlying cache implementation.
#
# Returns an array with the data for each of the names. For example:
# Returns a hash with the data for each of the names. For example:
#
# cache.write("bim", "bam")
# cache.fetch_multi("bim", "boom") {|key| key * 2 }
# # => ["bam", "boomboom"]
# cache.fetch_multi("bim", "boom") { |key| key * 2 }
# # => { "bam" => "bam", "boom" => "boomboom" }
#
def fetch_multi(*names)
options = names.extract_options!
options = merged_options(options)
results = read_multi(*names, options)
names.map do |name|
results.fetch(name) do
names.each_with_object({}) do |name, memo|
memo[name] = results.fetch(name) do
value = yield name
write(name, value, options)
value
......
......@@ -297,20 +297,21 @@ def test_fetch_multi
@cache.write('foo', 'bar')
@cache.write('fud', 'biz')
values = @cache.fetch_multi('foo', 'fu', 'fud') {|value| value * 2 }
values = @cache.fetch_multi('foo', 'fu', 'fud') { |value| value * 2 }
assert_equal(["bar", "fufu", "biz"], values)
assert_equal("fufu", @cache.read('fu'))
assert_equal({ 'foo' => 'bar', 'fu' => 'fufu', 'fud' => 'biz' }, values)
assert_equal('fufu', @cache.read('fu'))
end
def test_multi_with_objects
foo = stub(:title => "FOO!", :cache_key => "foo")
bar = stub(:cache_key => "bar")
foo = stub(:title => 'FOO!', :cache_key => 'foo')
bar = stub(:cache_key => 'bar')
@cache.write('bar', "BAM!")
@cache.write('bar', 'BAM!')
values = @cache.fetch_multi(foo, bar) {|object| object.title }
assert_equal(["FOO!", "BAM!"], values)
values = @cache.fetch_multi(foo, bar) { |object| object.title }
assert_equal({ foo => 'FOO!', bar => 'BAM!' }, values)
end
def test_read_and_write_compressed_small_data
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册