2012-08-10 82 views
0

它是Rails/Ruby。只是想知道是否有一個DRYer版本刪除重複在下面的代碼:未選擇重構的情況下

case params[:order] 
when 'rating_ascend' 
    order = {:order => 'rating_average ASC'} 
when 'rating_descend' 
    order = {:order => 'rating_average DESC'} 
when 'distance' 
    order = {:order => 'distance ASC'} 
else 
    order = {:order => 'distance ASC'} 
end 

謝謝。

回答

5

或當然,有。

order = case params[:order] 
    when 'rating_ascend' 
    {:order => 'rating_average ASC'} 
    when 'rating_descend' 
    {:order => 'rating_average DESC'} 
    else 
    {:order => 'distance ASC'} 
end 

甚至這個(我不會寫這樣的,但是這是烘乾機)

order = {:order => case params[:order] 
    when 'rating_ascend' then 'rating_average ASC' 
    when 'rating_descend' then 'rating_average DESC' 
    else 'distance ASC' 
end} 

當您簡化代碼到這個地步,你發現你有雙「距離ASC」的結果。這是一個錯字還是故意的?

+0

其實我只是不打算重複'距離ASC',但你們重構更多......不,它不是一種類型。這個「訂單」是一個可選參數。 – Victor 2012-08-10 13:27:55

+0

好的,進一步簡化:) – 2012-08-10 13:29:23

+0

爲什麼不通常寫第二種方法? – Victor 2012-08-10 13:30:51

3
order = {} 
order[:order] = case params[:order] 
when "rating_ascend" then "rating_average ASC" 
when "rating_descend" then "rating_average DESC" 
else "distance ASC" 
end 
+0

用於記住關於'then'關鍵字的+1。 – 2012-08-10 13:03:20

+0

我比分號更喜歡它。 – sawa 2012-08-10 13:04:09

+0

謝謝。今天學到了一些東西。 – Victor 2012-08-10 13:37:56

1

你可以像以前的答案,甚至使其更好地只是刪除不需要的情況下

when 'distance' 
    'distance ASC' 

因爲else部分將執行相同的。

order = {:order => case params[:order] 
    when 'rating_ascend' 
    'rating_average ASC' 
    when 'rating_descend' 
    'rating_average DESC' 
    else 
    'distance ASC' 
end} 
3
orders = {'rating_ascend' => 'rating_average ASC', 'rating_descend' => 'rating_average DESC', 'distance' => 'distance ASC'} 
Model.order(orders[params[:order]] || 'distance ASC') 
+0

不錯,謝謝:) – 2012-08-10 13:35:16

+0

謝謝。今天學到了一些東西。 – Victor 2012-08-10 13:38:52

2

使用 '提取方法' 重構模式:

def determine_order(order) 
    case order 
    when 'rating_ascend' 
    'rating_average ASC' 
    when 'rating_descend' 
    'rating_average DESC' 
    else 
    'distance ASC' 
end 

order = {:order => determine_order(params[:order])} 
0

怎麼樣創建與diferent選項的哈希,並使用取找到的選項,類似:

order = order_hash.fetch(params[:order], {:order => 'distance ASC'}) 

def order_hash 
    { 
    'rating_ascend' => {:order => 'rating_average ASC'}, 
    'rating_descend' => {:order => 'rating_average DESC'}, 
    'distance' => {:order => 'distance ASC'} 
    } 
end 

而且由於fetch可以採用默認選項作爲第二參數,因此您可以輕鬆解決e上的其他問題你的情況。

相關問題