ruby-on-rails - 如何在 Draper gem 中使用 i18n 翻译方法?

标签 ruby-on-rails ruby-on-rails-3 internationalization decorator

我使用 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/

相关文章:

ruby-on-rails - Rails 服务器启动后退出

ajax - 没有页面刷新,Rails 3 ajax 更新部分不起作用

ruby-on-rails - paypal_adaptive gem 的安全问题

mysql - 为什么 ruby​​ 检测不到无效编码而 mysql 检测到?

unicode - 关于 Unicode 我需要了解什么?

ruby-on-rails - Rails 应用程序给出错误 "can not load translations from {ru.yml path} expected it to return a hash, but does not"

ruby-on-rails - 无法在 ruby​​ on rails 中安装 pg gem

jquery - 如果字段为空,则阻止使用 jquery ujs 提交表单

mysql - Rails : Selecting from multiple tables using . 加入()

mysql - 如何让所有艺术家都没有视频和照片?