@@ -265,7 +265,7 @@ def first(limit_or_opts = nil)
265
265
if cached? && cache_loaded?
266
266
return limit ? documents . first ( limit ) : documents . first
267
267
end
268
- try_numbered_cache ( :first , limit , :first ) do
268
+ try_numbered_cache ( :first , limit ) do
269
269
if limit_or_opts . try ( :key? , :id_sort )
270
270
Mongoid ::Warnings . warn_id_sort_deprecated
271
271
end
@@ -374,13 +374,14 @@ def last(limit_or_opts = nil)
374
374
if cached? && cache_loaded?
375
375
return limit ? documents . last ( limit ) : documents . last
376
376
end
377
- try_numbered_cache ( :last , limit , :last ) do
377
+ res = try_numbered_cache ( :last , limit ) do
378
378
with_inverse_sorting ( limit_or_opts ) do
379
- if raw_docs = view . limit ( limit || 1 ) . to_a . reverse
379
+ if raw_docs = view . limit ( limit || 1 ) . to_a
380
380
process_raw_docs ( raw_docs , limit )
381
381
end
382
382
end
383
383
end
384
+ res . is_a? ( Array ) ? res . reverse : res
384
385
end
385
386
386
387
# Get's the number of documents matching the query selector.
@@ -616,10 +617,9 @@ def try_cache(key, &block)
616
617
# @param [ String, Symbol ] key The instance variable name
617
618
# @param [ Integer | nil ] n The number of documents requested or nil
618
619
# if none is requested.
619
- # @param [ Symbol ] meth Method to extract the correct number of elements.
620
620
#
621
621
# @return [ Object ] The result of the block.
622
- def try_numbered_cache ( key , n , meth , &block )
622
+ def try_numbered_cache ( key , n , &block )
623
623
unless cached?
624
624
yield if block_given?
625
625
else
@@ -628,11 +628,12 @@ def try_numbered_cache(key, n, meth, &block)
628
628
if !ret || ret . length < len
629
629
instance_variable_set ( "@#{ key } " , ret = Array . wrap ( yield ) )
630
630
elsif !n
631
- ret = ret . is_a? ( Array ) ? ret . first : ret
631
+ ret . is_a? ( Array ) ? ret . first : ret
632
632
elsif ret . length > len
633
- ret = ret . send ( meth , n )
633
+ ret . first ( n )
634
+ else
635
+ ret
634
636
end
635
- ret
636
637
end
637
638
end
638
639
0 commit comments