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.
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
Another option is the configuration gem which gives you similar dot notation usage, but also more advanced options like setting default values, and the config file is Ruby instead of YAML.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With