Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
LemonPie Avatar asked Dec 30 '15 20:12

LemonPie


Video Answer


2 Answers

: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.

like image 153
Simone Carletti Avatar answered Nov 07 '22 08:11

Simone Carletti


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")

like image 21
Leantraxxx Avatar answered Nov 07 '22 07:11

Leantraxxx