'rails i18n - How to handle case of a nil date being passed ie l(nil)
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?
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
I recently updated an application that uses jankeesvw's relaxed i18n method to Ruby 3.1 and found an issue with missing arguments.
The related change in the I18n gem is this: ruby-i18n/i18n#5eeaad7.
Also this Ruby 3 change is related: https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/
Updated the code with this:
module I18n
class << self
alias original_localize localize
def localize(object, locale: nil, format: nil, **options)
object.present? ? original_localize(object, locale: locale, format: format, **options) : ''
end
end
end
And it works again!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Hollands |
| Solution 2 | nslocum |
| Solution 3 | Spa |
