From 69d922a029c45025aa32b62f80f7e2d78c227ca2 Mon Sep 17 00:00:00 2001 From: Eric Davis Date: Fri, 16 Jan 2009 16:08:13 -0800 Subject: [PATCH] Refactored Rate#for to only get one record. #1920 --- app/models/rate.rb | 6 +++--- spec/models/rate_spec.rb | 12 ++++-------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/app/models/rate.rb b/app/models/rate.rb index cc6295d..d337dd1 100644 --- a/app/models/rate.rb +++ b/app/models/rate.rb @@ -26,7 +26,7 @@ class Rate < ActiveRecord::Base # API to find the Rate for a +user+ on a +project+ at a +date+ def self.for(user, project = nil, date = Date.today.to_s) - rates = Rate.find(:all, + rate = Rate.find(:first, :conditions => ["user_id IN (?) AND project_id IN (?) AND date_in_effect <= ?", user.id, project.id, @@ -34,7 +34,7 @@ class Rate < ActiveRecord::Base ], :order => 'date_in_effect DESC') - return nil if rates.empty? - return rates[0].amount + return nil if rate.nil? + return rate.amount end end diff --git a/spec/models/rate_spec.rb b/spec/models/rate_spec.rb index 1c1aa98..2cc42d8 100644 --- a/spec/models/rate_spec.rb +++ b/spec/models/rate_spec.rb @@ -157,34 +157,30 @@ describe Rate, 'for' do describe 'with a user, project, and date' do it 'should find all the rates for a user on the project before the date' do rate1 = mock_model(Rate, :amount => 50.50) - rate2 = mock_model(Rate, :amount => 100.25) - rates = [rate1, rate2] - Rate.should_receive(:find).with(:all, { + Rate.should_receive(:find).with(:first, { :conditions => ["user_id IN (?) AND project_id IN (?) AND date_in_effect <= ?", @user.id, @project.id, @date ], :order => 'date_in_effect DESC' - }).and_return(rates) + }).and_return(rate1) Rate.for(@user, @project, @date) end it 'should return the value of the most recent rate found' do rate1 = mock_model(Rate, :amount => 50.50) - rate2 = mock_model(Rate, :amount => 100.25) - rates = [rate1, rate2] - Rate.should_receive(:find).with(:all, { + Rate.should_receive(:find).with(:first, { :conditions => ["user_id IN (?) AND project_id IN (?) AND date_in_effect <= ?", @user.id, @project.id, @date ], :order => 'date_in_effect DESC' - }).and_return(rates) + }).and_return(rate1) Rate.for(@user, @project, @date).should eql(rate1.amount) end