Skip to content

Instantly share code, notes, and snippets.

@MattiSG
Created October 14, 2013 12:02
Show Gist options
  • Save MattiSG/6974568 to your computer and use it in GitHub Desktop.
Save MattiSG/6974568 to your computer and use it in GitHub Desktop.
Add number localization to Rails' `i18n` module.
module LocalizeHelper
# Wraps I18n.localize to add support for Numbers l12n.
#
# @param value [Numeric|DateTime|Time|Date] The value to localize.
# @return [String] The localized value.
# @see <https://github.com/svenfuchs/i18n/issues/135>
def localize(value)
if value.is_a?(Numeric)
number_with_delimiter(value, locale: I18n.locale)
else
I18n.l(value)
end
end
# Override the global `l` alias for localization.
alias_method :l, :localize
end
require 'spec_helper'
describe LocalizeHelper do
let(:locale) { 'en' }
before { I18n.locale = locale }
after { I18n.locale = 'en' }
subject { localize target }
context 'on a number' do
let(:target) { 9000 }
context 'in English' do
it { should == '9,000' }
end
context 'in French' do
let(:locale) { 'fr' }
it { should == '9 000' }
end
end
context 'on a date' do
let(:target) { Date.new(2001, 2, 3) }
context 'in French' do
let(:locale) { 'fr' }
it { should == '03/02/2001' }
end
end
end
@josegrad
Copy link

Great idea but I18n.localize can take more arguments than just the value.
As such the method you propose will fail if you require some specific format when localizing a date for example with I18n.l(adate, :format => :short) . The code can be improved, but I decided to just add a new method not tied to I18n.localize to avoid conflicts.

def ln(value)
    number_with_delimiter(value, locale: I18n.locale)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment