gpt4 book ai didi

ruby-on-rails - 覆盖 Rails 翻译助手

转载 作者:行者123 更新时间:2023-12-02 06:30:13 26 4
gpt4 key购买 nike

我要I18n.translate()I18n.t()使用特定的区域设置,但不使用I18n.locale。我不想使用I18n.t(:my_key, locale: :my_locale)每次,所以如果我可以重写函数本身那就太好了。

我尝试将其放入新的助手中:

# my_helper.rb
module MyHelper
def translate(key, options = {})
options[:locale] = MY_LOCALE
I18n.translate key, options
end
alias :t :translate
end

这对于像t('word')这样的“硬键”来说效果很好。 ,但找不到像 t('.title') 这样的“动态键”的正确路径,它应该使用我的部分路径,即 de.users.form.title .

感谢您的帮助!

最佳答案

以下功能之间似乎存在一些混淆:

I18n.translate 不会执行您所期望的“延迟查找”(即,如果查找键以点开头,则将查找键的范围限定为当前部分)。这是 ActionView::Helpers::TranslationHelper#translate 以及 some others 的一项功能。 .

您的方法正在重写 ActionView::Helpers::TranslationHelper#translate,而不调用 super 来实现延迟加载。因此,如果您想坚持重写该方法,我想您可能需要:

# my_helper.rb
module MyHelper
def translate(key, options = {})
# If you don't want to ignore options[:locale] if it's passed in,
# change to options[:locale] ||= MY_LOCALE
options[:locale] = MY_LOCALE
super(key, options)
end
alias :t :translate
end

就我个人而言,我宁愿每次在我的 View 中使用 t(:my_key, locale: :my_locale) 而无需覆盖,或者最多有一个单独的帮助器方法来包装调用到 ActionView::Helpers::TranslationHelper#translate 以及强制特定区域设置的额外业务逻辑。

关于ruby-on-rails - 覆盖 Rails 翻译助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26338337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com