2012-02-09 93 views
1

我有一個自定義的輔助方法,它輸出保存的百分比。例如,它將計算物品的折扣並輸出「20%折扣」。Rails I18n:根據語言環境調用不同的邏輯

我將網站本地化爲中文,而在中文中同樣的折扣表達方式不同。 「20%off」表示爲「8 Cut」「80%原價」。由於這兩個表達式是完全不同的,我想我需要編寫兩個版本的helper方法。

目前我寫的這個樣子,在助手自己檢查區域設置:

def percent_off(discount, locale=I18n.locale) 
     if not locale.to_s.include?('zh') 
     n = ((1 - (discount.preferential_price/discount.original_price)) * 100) .to_i 
     "#{n}% off" 
     else 
     # Chinese 
     n = ((discount.preferential_price/discount.original_price) * 10) .to_i 
     "#{n} cut" 
     end 
    end 

有沒有更好的方式來做到這一點?

回答

1

唯一不好的就是基爾在您的幫助,我可以看到的是,你寫percent_off折扣,但它不是顯而易見的東西,它會返回(所以我會在這裏創建2個不同的輔助方法。

是我使用注意在視圖區域檢查看起來並不漂亮,當你查看塊變成了不同的翻譯版本完全不同,所以我創建爲目的的國際化的輔助方法:

module ApplicationHelper 
    def translate_to(locales, &blk) 
    locales = [locales.to_s] if !locales.is_a?(Array) 
    yield if locales.include?(I18n.locale.to_s) 
    end 
    alias :tto :translate_to 
end 

和觀點:

<% tto :en do %> 
    <% # some en-translated routine %> 
<% end %> 
<% tto :zh do %> 
    <% # zh-translated routine %> 
<% end %> 

不知道這是管理翻譯塊的最佳方法,但我發現它很有用))

2

您可能想要重構代碼,以便計算用於表示折扣的數字與選擇/創建您的本地化消息。

這裏是沿着這些線路的一個想法:

在你en.yml

# value for "n% off" 
    discount_msg: "%{n}% off!" 

在你zh.yml

# value for "(100-n)% of original price" 
    discount_msg: "%{n}% of original price (in Chinese)" 

下一頁重構percent_off的輔助方法,以便它只計算正確的價值折扣價值取決於隱含的語言環境:

def percent_off(discount) 
    n = ((1 - (discount.preferential_price/discount.original_price)) * 100) .to_i  
    if I18n.locale.to_s.include?('zh') 
    n = 100 - n 
    end 
    n 
end 

然後,你可以調用上面是這樣的:

I18n.t('discount_msg', :n=>percent_off(discount)) 
+0

我覺得現在您的解決方案是最乾淨的,但由於每個地區的措辭和邏輯都非常緊密耦合,我覺得把它們放在一起品牌管理他們更容易。 – lulalala 2012-02-10 06:20:21