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?
: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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With