2014-01-06 35 views
0

我有一個心智塊,我有一段代碼,我想保留在一個方法中,但以一種乾淨的方式。以更清晰的方式重寫代碼

這是這裏的想法;

def self.number_price(user_id,to) 
    user = User.find(user_id) 
    user_prices = user.prices 
    user_prices.each do |price| 
     if to =~ /^(#{price.prefix})/ 
     return price.send("price_#{user.currency.downcase}").to_f 
     end 
    end 
end 

但是,如果下面的循環不返回任何東西,我想返回這個;

return DefaultPrices.send("price_#{user_currency.downcase}").to_f 

否則,該方法將默認返回user_prices = user.prices

有人結果表明這樣的一些乾淨的方式.. 謝謝

+1

如果您幫助我們理解代碼在更高級別上應該做什麼,例如通過至少解釋預期的輸入和輸出,您會更成功地獲得答案。 –

+0

您可以使用http://www.ruby-doc.org/core-2.1.0/Enumerable.html#method-i-find – akonsu

+0

所有已經回答的人似乎都知道對象DefaultPrices是什麼。我不。請解釋。 –

回答

1

有什麼不好的明顯嗎? (三角洲處理用戶沒有找到。)

def self.number_price(user_id, to) 
    user = User.find(user_id) 
    user.prices.each do |price| 
    return price.send("price_#{user.currency.downcase}").to_f if to =~ /^(#{price.prefix})/ 
    end 

    DefaultPrices.send("price_#{user_currency.downcase}").to_f 
end 
+0

我覺得'DeafualtPrices'前面的回報是個問題,當你累了就看不到明顯的問題。謝謝 – Acacia

+0

@ user2963716你仍然可以使用'return',這只是典型的Ruby經常省略隱含的東西。也就是說,我傾向於另外兩個答案所顯示的進一步重構 - 我只是試圖保持相同的形式。 –

+0

我同意用'user'替換'user_id'參數會是一個改進,但我認爲'if'在這裏是爲了易讀性,而爲了可讀性需要'1',並且爲(怪異)-1加1。 –

4
def self.number_price(user_id, to) 
    user = User.find(user_id) 
    price = user.prices.find {|price| to =~ /^(#{price.prefix})/ } || DefaultPrices 
    price.send("price_#{user.currency.downcase}").to_f 
end 
+0

雖然縮短了方法並添加了默認價格,但這非常繁忙。這可以說是難以閱讀。 –

+1

更好嗎?:'user.prices.find(DefaultPrices){| price | to =〜/^(#{price.prefix})/}' – exbinary

+0

'#find'參數必須是_callable_。傳遞'DefaultPrices'不起作用 – wacko

1

我認爲使用Enumerable#find是你在找什麼。我可能會做這樣的事情:

def self.number_price(user_id,to) 
    prices = User.find(user_id).prices 
    price = prices.find {|p| to =~ /^(#{p.prefix})/} || DefaultPrices 

    price.send("price_#{user.currency.downcase}").to_f 
end 

但如果可能的話,我想重構出user_id,並傳遞給用戶。這樣這個類不需要知道用戶是如何實現的,它只是知道它有一個價格方法。

def self.number_price(user,to) 
    price = user.prices.find {|p| to =~ /^(#{p.prefix})/} || DefaultPrices 

    price.send("price_#{user.currency.downcase}").to_f 
end 

你可以進一步,但這似乎是一個很好的方法來處理它。

+0

這看起來更好。 –

+0

'user = User.find(user_id)。價格'返回的價格,而不是用戶 – wacko

+0

我認爲邏輯重構使這是最好的答案,在原來的問題的約束。 –