ruby - I18n : how can I guard against empty interpolation arguments?

标签 ruby internationalization

给定以下 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/

相关文章:

ruby-on-rails - 如果对象为空,获取属性的更好方法

android - 如何在android中设置不同的语言环境?

ruby-on-rails - 如何在 Rails 中构造 i18n yaml 文件?

spring - Jhipster 改变语言

java - Spring MVC i18n 验证错误消息

sql-server - 1/1/1753 在 SQL Server 中有何意义?

ruby - 将 proc 设置为默认方法参数

ruby - 类方法 : describe "#my_class_method" or describe "#self.my_class_method"?

ruby-on-rails - 如何将一个类迁移为另一个类的子类?

ruby-on-rails - 是否可以卸载 ruby​​ gems、rails 等并进行完整的全新安装?