Permalink
Browse files

Refactored ActiveRecord `first` method to get rid of duplication.

  • Loading branch information...
1 parent 7a32c63 commit d5450a6659a33ef08a170afcaae084023bcd275b @dmitry dmitry committed Jun 9, 2013
Showing with 10 additions and 11 deletions.
  1. +10 −11 activerecord/lib/active_record/relation/finder_methods.rb
View
21 activerecord/lib/active_record/relation/finder_methods.rb
@@ -81,11 +81,7 @@ def take!
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
def first(limit = nil)
if limit
- if order_values.empty? && primary_key
- order(arel_table[primary_key].asc).limit(limit).to_a
- else
- limit(limit).to_a
- end
+ find_first_records(order_values, limit)
else
find_first
end
@@ -307,12 +303,15 @@ def find_first
if loaded?
@records.first
else
- @first ||=
- if with_default_scope.order_values.empty? && primary_key
- order(arel_table[primary_key].asc).limit(1).to_a.first
- else
- limit(1).to_a.first
- end
+ @first ||= find_first_records(with_default_scope.order_values, 1).first
+ end
+ end
+
+ def find_first_records(order_values, limit)
+ if order_values.empty? && primary_key
+ order(arel_table[primary_key].asc).limit(limit).to_a
+ else
+ limit(limit).to_a
end
end

0 comments on commit d5450a6

Please sign in to comment.