【问题标题】:Custom rails configuration section自定义 rails 配置部分
【发布时间】:2013-09-17 02:09:08
【问题描述】:

为 Rails 应用程序创建自定义配置部分的最佳方法是什么?理想情况下,我希望最终结果是一个 api 调用,例如:

Rails.configuration.foo.bar
Rails.configuration.foo.baz

例如

Rails.configuration.stackoverflow.api_key
Rails.configuration.stackoverflow.api_secret

我会将 stackoverflow 配置存储在某个 .rb 文件(config/initializers?)中,我显然会在 Rails.configuration 中拥有其他类似命名空间的文件

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你要找的是ActiveSupport::OrderedOptions

    rails 内部使用它来设置配置命名空间。它允许在config/application.rb 中做这样的事情:

    module MyApp
      class Application < Rails::Application
        # ...
        config.foo = ActiveSupport::OrderedOptions.new 
        config.foo.bar = :bar
      end
    end
    

    然后您可以按通常的方式检索它:

    Rails.configuration.foo.bar
    

    如果您希望它是特定于环境的,您也可以在 config/environments/*.rb 而不是 config/application.rb 中使用它。

    【讨论】:

      【解决方案2】:

      在 Rails 4 中使用 custom-configuration 更好。

      $ Rails.configuration.x.class
      # Rails::Application::Configuration::Custom < Object
      
      Rails.application.configure do    
        # custom configuration section
        config.x.foo.bar = "foo.bar"
      end
      
      $ Rails.configuration.x.foo.bar
      # "boo.bar"
      

      【讨论】:

        猜你喜欢
        • 2010-10-25
        • 2010-11-12
        • 2011-07-04
        • 2012-12-12
        • 2013-09-21
        • 2014-01-19
        • 2011-10-02
        • 1970-01-01
        相关资源
        最近更新 更多