2012-02-27 56 views

回答

5

不幸的是,沒有內置的解決方案。見post

您可以定義自己的助手,提供「無」人類可讀值。例如:

def ldate(dt) 
    dt ? l(dt) : t("[???]") 
end 
13

爲了延長拉里K公司的回答,

助手應包括散列通選項的I18n。

def ldate(dt, hash = {}) 
    dt ? l(dt, hash) : nil 
end 

這使您可以通過選擇這樣的:

= ldate @term.end_date, format: :short 
18

我覺得這是解決這個問題一個更清潔的方式。我猴子打補丁的I18n名爲relaxed_i18n.rb

一個初始化這是該文件的內容:

module I18n 

    class << self 

    alias_method :original_localize, :localize 

    def localize object, options = {} 
     object.present? ? original_localize(object, options) : '' 
    end 

    end 

end 

這是RSpec的代碼我用來驗證這種方法的輸出:

require 'spec_helper' 

describe 'I18n' do 

    it "doesn't crash and burn on nil" do 
    I18n.localize(nil).should == '' 
    end 

    it 'returns a date with Dutch formatting' do 
    date = Date.new(2013, 5, 17) 
    I18n.localize(date, format: '%d-%m-%Y').should == '17-05-2013' 
    end 

end 
+0

太棒了!它使用Rails 4.2.0完美工作。 – anka 2015-03-06 09:32:09