Rails application settings?

℡╲_俬逩灬. 提交于 2019-11-30 13:11:42

For general application configuration that doesn't need to be stored in a database table, I like to create a config.yml file within the config directory. For your example, it might look like this:

defaults: &defaults
  app_title: My Awesome App
  header_colour: #fff

development:
  <<: *defaults

test:
  <<: *defaults
  app_title: My Awesome App (TEST ENV)

production:
  <<: *defaults

This configuration file gets loaded from a custom initializer in config/initializers:

Rails 2.x:

APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]

Rails 3.x:

APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

You can then retrieve the value using:

title = APP_CONFIG['app_title']

See this Railscast for full details.

There is pretty nice plugin/gem Settingslogic.

  # app/config/application.yml
  defaults: &defaults
    cool:
      saweet: nested settings
    neat_setting: 24
    awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>

  development:
    <<: *defaults
    neat_setting: 800

  test:
    <<: *defaults

  production:
    <<: *defaults

You can use these settings anywhere, for example in a model:

  class Post < ActiveRecord::Base
    self.per_page = Settings.pagination.posts_per_page
  end

Here's what I did, and it seems most people follow this approach too: http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!