我使用 Draper gem 来装饰我的模型。这里我有非常经典的设置:
# app/decorators/subject_decorator.rb
class SubjectDecorator < ApplicationDecorator
decorates :subject
def edit_link
h.link_to(h.t('.edit'), '#')
end
end
我使用 i18n 进行国际化。但是当我运行这个时,我得到:
Cannot use t(".edit") shortcut because path is not available
所以我想知道以前是否有人这样做过?它应该非常简单。
最佳答案
问题是你不能利用 lazy lookup在装饰器中,因为它们没有任何上下文来确定 View 文件级别(索引、显示、编辑等)。所以开箱即用,您只需要拼出整个内容,例如 t('subjects.show.edit')
管他呢。
这是我最终为让它对我有用而做的事情。
class ApplicationDecorator < Draper::Base
def translate(key, options={})
if key.to_s[0] == '.'
key = model_class.to_s.downcase.pluralize + key
end
I18n.translate(key, options)
end
alias :t :translate
end
这不会让你得到完整的
subjects.show.edit
引用,你只会得到 subjects.edit
但对我来说似乎总比没有好。
关于ruby-on-rails - 如何在 Draper gem 中使用 i18n 翻译方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7819885/