我正在處理大量遺留數據,偶爾datetime字段爲零/空。這打破了本地化。有沒有推薦的方法來解決這個問題:rails i18n - 如何處理無日期通過的情況,即l(無)
dt = nil
l(dt) unless dt.nil?
我正在處理大量遺留數據,偶爾datetime字段爲零/空。這打破了本地化。有沒有推薦的方法來解決這個問題:rails i18n - 如何處理無日期通過的情況,即l(無)
dt = nil
l(dt) unless dt.nil?
爲了延長拉里K公司的回答,
助手應包括散列通選項的I18n。
def ldate(dt, hash = {})
dt ? l(dt, hash) : nil
end
這使您可以通過選擇這樣的:
= ldate @term.end_date, format: :short
我覺得這是解決這個問題一個更清潔的方式。我猴子打補丁的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
太棒了!它使用Rails 4.2.0完美工作。 – anka 2015-03-06 09:32:09
當然這裏的第二行永遠不會執行? – Yule 2012-02-27 15:02:27