svenfuchs/rails-i18n — Issue #169: Reflexive Interpolation
Author: leehambley
Created: 2011-12-15 13:56:34+00:00
State: open

Further to a very brief twitter exchange I just had with @svenfuchs on Twitter, I thought I would write this here, that there might be a discussion about the merits of this option.

Given the following YAML file:

``` yaml
de:
virtual_currency:
one: "Jelly Bean"
other: "Jelly Beans"
products:
index:
title: "Earn Jelly Beans by retweeting @svenfuchs"
show:
title: "Earn Jelly Beans by retweeting @svenfuchs, spend your Jelly Beans on %{product_name}"
```

A naturally stupid and contrived example, not the frequent duplication of` `Jelly Beans`.

Whilst it's [clear that I18n isn't DRY](), the name of our virtual currency is re-re-reused in a multitude of places, and it's always the `.other` subkey. There's one edge-case when it's only `one` **Jelly Bean**.

Our solution so far, then looks like this:

``` yaml
de:
virtual_currency:
one: "Jelly Bean"
other: "Jelly Beans"
products:
index:
title: "Earn %{virtual_currency} by retweeting @svenfuchs"
show:
title: "Earn %{virtual_currency} by retweeting @svenfuchs, spend your %{virtual_currency} on %{product_name}"
```

And in every place it's used, `t(:'.title', virtual_currency: t('virtual_currency'), product_name: @product.name)`. This is a little tedious.

To that end, I have a modification to `I18n::Backend::Simple` (WIP, will probably become a `Defaultnterpolations` backend in it's own right) that looks something like this:

``` ruby
module I18n
module Backend
class Simple
def interpolate(locale, string, values = {})
super(locale, string, values.merge({
virtual_currency: I18n.t('virtual_currency.other')
}))
end
end
end
end
```

Would it be possible, advisable, or well received to implement an alternative interpolation syntax, perhaps the immortal `{{…}}` which would do what I want to call **reflexive interpolation**, here's an example, only YAML, there's no code changes:

``` yaml
de:
virtual_currency:
one: "Jelly Bean"
other: "Jelly Beans"
products:
index:
title: "Earn {{virtual_currency.other}} by retweeting @svenfuchs"
show:
title: "Earn {{virtual_currency.other}} by retweeting @svenfuchs, spend your %{virtual_currency.other} on %{product_name}"
```

There's some flaws, I am sure, and one broken, yet seemingly similarly targeted implementation [here](http://blog.eizesus.com/2011/02/Rails_I18n:_default_interpolation_values-26-2-2011/). From which I drew the original idea for the soluton.