Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 232
recursive_acronym Avatar asked Feb 27 '12 14:02

recursive_acronym


3 Answers

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
like image 74
Jankeesvw Avatar answered Oct 23 '22 14:10

Jankeesvw


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
like image 27
nslocum Avatar answered Oct 23 '22 12:10

nslocum


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
like image 7
Larry K Avatar answered Oct 23 '22 13:10

Larry K