I am working on a Rails application that has user authentication which provides an administrators account. Within the administrators account I have made a p开发者_开发知识库age 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!
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/
精彩评论