rails i18n - How to handle case of a nil date being passed ie l(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