Rails application settings?

前提是你 提交于 2019-12-18 15:30:37

问题


I am working on a Rails application that has user authentication which provides an administrators account. Within the administrators account I have made a page for sitewide settings.

I was wondering what the norm is for creating these settings. Say for example I would like one of the settings to be to change the name of the application name, or change a colour of the header.

What I am looking for is for someone to explain the basic process/method - not necessarily specific code - although that would be great!


回答1:


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.




回答2:


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



回答3:


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/



来源:https://stackoverflow.com/questions/2907643/rails-application-settings

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