Skip to content

Commit

Permalink
DRY up first/last and hence make last benefit from the bugfix in first
Browse files Browse the repository at this point in the history
  • Loading branch information
jonleighton committed Jan 30, 2011
1 parent e8d7152 commit b7bcc7e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
Expand Up @@ -36,25 +36,12 @@ def find(*args)
end
end

# Fetches the first one using SQL if possible.
def first(*args)
if fetch_first_or_last_using_find?(args)
scoped.first(*args)
else
load_target unless loaded?
args.shift if args.first.kind_of?(Hash) && args.first.empty?
@target.first(*args)
end
first_or_last(:first, *args)
end

# Fetches the last one using SQL if possible.
def last(*args)
if fetch_first_or_last_using_find?(args)
scoped.last(*args)
else
load_target unless loaded?
@target.last(*args)
end
first_or_last(:last, *args)
end

def to_ary
Expand Down Expand Up @@ -560,6 +547,17 @@ def find_by_scan(*args)
load_target.select { |r| ids.include?(r.id) }
end
end

# Fetches the first/last using SQL if possible, otherwise from the target array.
def first_or_last(type, *args)
if fetch_first_or_last_using_find?(args)
scoped.send(type, *args)
else
load_target unless loaded?
args.shift if args.first.kind_of?(Hash) && args.first.empty?
@target.send(type, *args)
end
end
end
end
end
Expand Up @@ -86,10 +86,16 @@ def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(:name => 'honda')
bulbs = Car.first.bulbs
bulbs.inspect # to load all instances of bulbs

assert_no_queries do
bulbs.first()
bulbs.first({})
end

assert_no_queries do
bulbs.last()
bulbs.last({})
end
end

def test_create_resets_cached_counters
Expand Down

0 comments on commit b7bcc7e

Please sign in to comment.