Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolation in I18n array

I'm using arrays in a locale file to be able to generate blocks of text in various output methods (ActionMailer templates, Prawn documents, HAML templates) that are locale-specific. It works perfectly, but sometimes I want to pass variables into these I18n calls. However, this doesn't work.

Say my locale file looks like this:

en:
  my_array:
    - "Line 1"
    - "Line 2"
    - "Line 3 has a %{variable}"
    - "Line 4"

I want the output of I18n.t('my_array', :variable => 'variable named variable') to be as follows:

["Line 1", "Line 2", "Line 3 has a variable named variable", "Line 4"]

However, the output is:

["Line 1", "Line 2", "Line 3 has a %{variable}", "Line 4"]

Will I have to do the interpolation myself after retrieving the array? Or is there a better way to do this?

like image 451
Jaap Haagmans Avatar asked Feb 05 '14 10:02

Jaap Haagmans


1 Answers

I think such thing is not supported natively in i18n gem, but it's doable using some meta-programming magic.

In an initializer (say, config/initializers/i18n.rb) add the following

I18n.backend.instance_eval do
  def interpolate(locale, string, values = {})
    if string.is_a?(::Array) && !values.empty?
      string.map { |el| super(locale, el, values) }
    else
      super
    end
  end
end
like image 149
Ahmad Sherif Avatar answered Sep 20 '22 13:09

Ahmad Sherif