【问题标题】:Reference YAML keyword file for DRY controller code参考 DRY 控制器代码的 YAML 关键字文件
【发布时间】:2016-10-27 11:54:16
【问题描述】:

我希望能够在整个 Rails 应用程序中使用全局可访问的符号,以便打印或返回一组易于维护的字符串/句子。我之前听说过一种使用 YAML 的方法,但我不记得它的实现细节或它的名称。

我理想中的一个例子:

控制器

def foo
  if token.expired?
    render json: { message: :token_expiry_message }
  end
end

def bar
  if !user.authenticate
    flash[:notice] = :token_expiry_message
  end
end

Yaml 文件某处

token_expiry_message: "The user token is expired, please re-authenticate"

通过这种方式,我可以通过从 YAML 文件中引用控制器代码并在整个应用程序中使用标准语言集。

【问题讨论】:

  • 只使用位于 config/locales 中的语言环境文件。您可以在 application.rb - config.i18n.default_locale = :en 中设置默认语言环境,这将映射到 config/locales 中的 en.yml

标签: ruby-on-rails yaml


【解决方案1】:

您可以使用内置的国际化工具轻松做到这一点

http://guides.rubyonrails.org/i18n.html

in config/locals/locale.yml(locale 是您当前的本地语言,例如 en)..

 en:
     token_expiry_message: "Your token has expired, please get another"

那么您可以只使用t() 助手。有这样的

  def foo
      if token.expired?
        render json: { message: t(:token_expiry_message) }
      end
    end

    def bar
      if !user.authenticate
        flash[:notice] = "Error: " + t(:token_expiry_message)
      end
    end

具有能够提供错误消息的本地化版本的额外好处。

【讨论】:

  • 我喜欢这个实现。谢谢!
【解决方案2】:

是的,您可以为此使用 Settings.yml 文件。如果您需要支持多种语言,您还可以深入了解它并使用本地化文件。

在您的 Settings.yml 中:

token_expiry_message: 'The user token is expired, please re-authenticate'

然后可以通过以下方式将其加载到您的代码中:

def foo
  if token.expired?
    render json: { message: Settings.token_expiry_message }
  end
end

def bar
  if !user.authenticate
    flash[:notice] = "Error: #{Settings.token_expiry_message}"
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    相关资源
    最近更新 更多