I am working with a lot of legacy data and occasionally a datetime field is nil/null. This breaks the localization. Is there a recommended way of fixing this aside from doing this:
dt = nil
l(dt) unless dt.nil?
I think there is a cleaner way to fix this. I monkey patched I18n in an initializer called relaxed_i18n.rb
This is the content of that file:
module I18n
class << self
alias_method :original_localize, :localize
def localize object, options = {}
object.present? ? original_localize(object, options) : ''
end
end
end
And this is the RSpec code I used to validate the output of this method:
require 'rails_helper'
describe 'I18n' do
it "doesn't crash and burn on nil" do
expect(I18n.localize(nil)).to eq ''
end
it 'returns a date with Dutch formatting' do
date = Date.new(2013, 5, 17)
expect(I18n.localize(date, format: '%d-%m-%Y')).to eq '17-05-2013'
end
end
To extend Larry K's answer,
The helper should include a hash to pass options to I18n.
def ldate(dt, hash = {})
dt ? l(dt, hash) : nil
end
This allows you to pass options like this:
= ldate @term.end_date, format: :short
Unfortunately, there is no built-in solution. See post.
You can define your own helper that supplies the "nil" human-readable value. Eg:
def ldate(dt)
dt ? l(dt) : t("[???]")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With