views:

53

answers:

4

I have a rails app and from the admin section of the site I'd like to be able to enable / disable certain settings such as serving ads or embedding of Google Analytics tracking code.

Is there a best practice for this in Rails? One thought was creating a settings table and storing values in it.

A: 

You can store your config in the config/ directory. I know a few applications that store their configs in that directory. (e.g. teambox.yml in Teambox).

floatless
A: 

I would store this information in a database unless you don't have access to one. If you do not have access to a database, you could store the file in the config folder.

Here is example controller code for reading from and writing to a config file.

def featured_specials
  @featured_specials = YAML::load_file("#{RAILS_ROOT}/config/featured_specials.yml")
end

def save_featured_specials
  config_file = "#{RAILS_ROOT}/config/featured_specials.yml"
  File.new(config_file, "w") unless File.exist?(config_file)
  File.open(config_file, "w") do |f|
    f.write(params['formvars'].to_yaml)
  end
  flash[:notice] = 'Featured Specials have been saved.'
  redirect_to :action => 'featured_specials'
end

NOTE: this code could be cleaned up quite a bit, but should serve as a decent example.

Phil
+1  A: 

If you're not going for run-time configuration, then you might use something like rbates' nifty-config generator: http://github.com/ryanb/nifty-generators

I've used it for simple, build-time configuration settings. So, for instance, when storing payment gateway credentials for an ecommerce site, my load_gateway_config.yml looks like this:

require 'ostruct'

raw_config = File.read(Rails.root + "config/gateway_config.yml")
GATEWAY_CONFIG = YAML.load(raw_config)[Rails.env].symbolize_keys

#allow dot notation access
GatewayConfig = OpenStruct.new(GATEWAY_CONFIG)

Then, to grab a setting from your config file, you'll call something like

GatewayConfig.username
lukewendling
A: 

I already upvoted a different answer, but for a quick-and-dirty way you can drop a class variable in environment.rb, after the block of initializer code.

tlianza