给定以下 i18n key :
greeting: "Hi %{name}! Feeling %{adjective}?"
如果我打电话
I18n.t!("greeting", adjective: "strigine")
,我得到一个异常(exception):I18n::MissingInterpolationArgument
.这很好。但是,如果我根本不传递任何参数,我只会得到原始字符串。
I18n.t!("greeting") # => "Hi %{name}! Feeling %{adjective}?"
我想确保这不会发生。 如果没有给出参数,是否有此方法调用的版本 ,还是我必须自己编码?
最佳答案
I18n 是故意这样做的
原因是documented in the tests如下:
If no interpolation parameter is not given, I18n should not alter the string. This behavior is due to three reasons:
- Checking interpolation keys in all strings hits performance, badly;
- This allows us to retrieve untouched values through I18n. For example I could have a middleware that returns I18n lookup results in JSON to be processed through Javascript. Leaving the keys untouched allows the interpolation to happen at the javascript level;
- Security concerns: if I allow users to translate a web site, they can insert %{} in messages causing the I18n lookup to fail in every request.
如何解决它
如果你想在这种情况下出现异常,你可以定义一个这样的方法:
# Needed because I18n will happily return the raw template string if given
# no interpolation arguments
# https://github.com/svenfuchs/i18n/blob/v0.7.0/lib/i18n/tests/interpolation.rb#L6-L21
def i18n_strict_t!(key, options = {})
localized = I18n.t!(key, options)
if missing = localized.match(I18n::INTERPOLATION_PATTERN)
fail I18n::MissingInterpolationArgument.new(
missing.captures.first, options, localized
)
end
localized
end
用法:
i18n_strict_t!("greeting")
# => I18n::MissingInterpolationArgument: missing
# interpolation argument "name" in
# "Hi %{name}! Feeling %{adjective}?" ({} given)
i18n_strict_t!("greeting", name: "Carla", adjective: "taciturn")
# => "Hi Carla! Feeling taciturn?"
或者对于更慢但更简单的实现:
def i18n_strict_t!(key, options = {})
options[:force_interpolation] = true if options.empty?
I18n.t!(key, options)
end
关于ruby - I18n : how can I guard against empty interpolation arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191510/