Permalink
Browse files

Use LIMIT sql word in last when it's possible

  • Loading branch information...
1 parent 451cdd6 commit 5f5527c726841cdefb82965a645d554767c5a6a9 @dmathieu dmathieu committed Sep 5, 2011
@@ -134,7 +134,11 @@ def first!
def last(*args)
if args.any?
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
- to_a.last(*args)
+ if order_values.empty? && reorder_value.nil?
+ order("#{primary_key} DESC").limit(*args).reverse
+ else
+ to_a.last(*args)
+ end
else
apply_finder_options(args.first).last
end
@@ -243,8 +243,25 @@ def test_model_class_responds_to_last_bang
end
end
- def test_first_with_integer_should_use_sql_limit
+ def test_first_and_last_with_integer_should_use_sql_limit
assert_sql(/LIMIT 2/) { Topic.first(2).entries }
+ assert_sql(/LIMIT 5/) { Topic.last(5).entries }
+ end
+
+ def test_last_with_integer_and_order_should_keep_the_order
+ assert_equal Topic.order("title").to_a.last(2), Topic.order("title").last(2)
+ end
+
+ def test_last_with_integer_and_order_should_not_use_sql_limit
+ query = assert_sql { Topic.order("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
+ end
+
+ def test_last_with_integer_and_reorder_should_not_use_sql_limit
+ query = assert_sql { Topic.reorder("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
end
def test_first_and_last_with_integer_should_return_an_array

0 comments on commit 5f5527c

Please sign in to comment.