2011-10-06 76 views
0

這裏是我的代碼簡短的樣本:DRY - 多行代碼執行相同的更新功能

def update_records! 

    # Teams. 
    home_team_record = PoolRecord.for_recordable_and_user(event_home_team, user) 
    home_team_record.update_for!(self) 

    away_team_record = PoolRecord.for_recordable_and_user(event_away_team, user) 
    away_team_record.update_for!(self) 

    # Division(s). 
    home_team_div_record = PoolRecord.for_recordable_and_user(event_home_team_division, user) 
    home_team_div_record.update_for!(self) 

    # Create/update PoolRecord for away_team division if they're in a different division. 
    unless event_away_team_division == event_home_team_division 
    away_team_div_record = PoolRecord.for_recordable_and_user(event_away_team_division, user) 
    away_team_div_record.update_for!(self) 
    end 

    # User. 
    user_record = PoolRecord.for_recordable_and_user(user, user) 
    user_record.update_for!(self) 

end 

DRY'ing這段代碼實際上是相當簡單的,如果不是因爲需要的條件檢查away_team部門。我可以創建一個傳入的第一個參數的字符串數組,並傳送給對象#。但是,就像我說的,我需要在一種情況下檢查一個條件。你會如何推薦DRY'ing?

回答

4

一個簡單的助手將減少噪音:

def update_records! 
    update_one(event_home_team) 
    update_one(event_away_team) 
    update_one(event_home_team_division) 
    update_one(event_away_team_division) unless event_away_team_division == event_home_team_division 
    update_one(user) 
end 

private 

def update_one(team) 
    PoolRecord.for_recordable_and_user(team, user).update_for!(self) 
end 

如果因爲某些原因,你想利用它的另一個步驟,你可以做這樣的事情:

def update_records! 
    [ 
     [ event_home_team,   true ], 
     [ event_away_team,   true ], 
     [ event_home_team_division, true ] 
     [ event_away_team_division, event_away_team_division != event_home_team_division ], 
     [ user,      true ] 
    ].each do |team, do_it| 
     if(do_it) 
      PoolRecord.for_recordable_and_user(team, user).update_for!(self) 
     end 
    end 
end 

或者,根據在您的數據上,這可能工作:

def update_records! 
    [ 
     event_home_team, 
     event_away_team, 
     event_home_team_division, 
     event_away_team_division, 
     user 
    ].uniq.each do |team| 
     PoolRecord.for_recordable_and_user(team, user).update_for!(self) 
    end 
end 

這最後一個替換單個unless a == b條件在您的原始與一個簡單的uniq過濾器。

我不知道你的數據的確切屬性或你想要採取多遠,所以我提供了一些想法。我認爲最後一個最接近「說出你的意思」,但也許不是。

+0

非常優雅。謝謝您的幫助。 – keruilin