在 Rails 4 中,我可以在哪里存储站点范围的变量? [英] Where can I store site-wide variables in Rails 4?

查看:36
本文介绍了在 Rails 4 中,我可以在哪里存储站点范围的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 新手,有 ColdFusion 背景,我们将在应用程序"范围内存储全局/站点范围的变量.这会在任何视图或控制器中保持变量.Rails 4 是否具有此类功能的等效功能?

I am new to Rails and come from a ColdFusion background, where we would store global / site-wide variables in the 'application' scope. This persists the variable across any view or controller. Does Rails 4 have an equivalent functionality for this type of thing?

站点范围的变量通常不会经常更改,因此不需要以任何方式进行保护.

The site-wide variable won't typically change often so it doesn't need protecting in any way.

例如,在我的情况下,我想存储网站的域名.一种用于测试,一种用于实时环境.本地主机用于开发,xxxxxx.com 用于生产.

For example, in my situation, I want to store the website's domain name. One for testing and one for live environments. Localhost for development and xxxxxx.com for production.

任何提示或指示都会有所帮助.我已经在谷歌上广泛地搜索了这个,解决方案似乎太复杂了,无法完成似乎如此微不足道的任务.Rails 4 的最佳优雅解决方案是什么?

Any tips or pointers would help. I have Googled this extensively and solutions seem to be far too complicated to achieve what seems to be such a trivial task. What's the best elegant solution for Rails 4?

推荐答案

最简单、基本和默认的方式是使用 Rails.application.config 存储.

The simplest, basic and default way is to use the Rails.application.config store.

Rails.application.config.my_config = 'foo'

您可以在您的环境中分配一个配置:

You can assign a config in your environment:

# application.rb
module MyApp
  class Application < Rails::Application
    config.my_config = 'foo'
  end
end

和阅读它

Rails.application.config.my_config
# => 'foo'

这种方法适用于非常简单的应用程序,但如果您想要更高级的应用程序,可以使用多种 gem.

This approach works well for very simple applications, but if you want something more advanced there are several gems available.

我目前正在使用 SimpleConfig.主要优点是:

I'm currently using SimpleConfig. The main advantages are:

  • 每个环境的配置.您可以为应用程序配置默认配置,然后使用特定于环境的配置覆盖默认值
  • local.rb 自定义覆盖文件
  • capistrano 类似配置风格
  • 它与 dotenv gem 配合得很好,对于避免存储非常有用存储库中的敏感凭据.
  • per-environment configuration. You can configure default configurations for the application, then override defaults with environment specific configurations
  • local.rb file for custom overrides
  • capistrano-like configuration style
  • it works nicely with the dotenv gem, very useful to avoid storing sensitive credentials in your repo.

这篇关于在 Rails 4 中,我可以在哪里存储站点范围的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆