LemonPie
LemonPie

Reputation: 846

I18n.t Translation Missing Default Value Nil

So I know how return a default value if I get "translation missing:" when reading a yaml file.

some = I18n.t("something.something_else", default: "value")

But how do I do that in the Ruby way if I want the default value to be nil? I know I can regex and match for "translation missing:" from the variable some and if it matches, I would have it assign to nil. But what I wanted to do is have

some = I18n.t("something.something_else", default: nil)

But it just returned translation missing for me. Does anyone know a good way?

Upvotes: 13

Views: 12722

Answers (3)

Shai Coleman
Shai Coleman

Reputation: 898

This works as expected with newer version of Rails (v6.1 and later).

some = I18n.t("something.something_else", default: nil) returns nil as expected

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176542

:default can't be nil. Setting the value to nil is equivalent to not set the option at all.

However, since the gem seems to only check whether the key is nil or not, you can try to pass an empty string as a default value. It is possible the translate method will return an empty string in case of a missing translation.

some = I18n.t("something.something_else", default: "")

I believe this is the closer solution you can get, unless you define your custom translate method that internally lookups the presence of the key and returns nil if the key doesn't exist.

Upvotes: 24

Leantraxxx
Leantraxxx

Reputation: 4606

Try this some = I18n.t!("something.something_else") rescue nil

Ok, it's a bad practice to perform a rescue nil but, it's short and cute :)

You can do something like this

def translate(key)
  I18n.t!(key)
rescue I18n::MissingTranslationData
  nil
end

Then...

some = translate("something.something_else")

Upvotes: 8

Related Questions