Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I store a site sitewide configuration setting for a Rails app?

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.

like image 354
Moe Avatar asked Oct 15 '22 01:10

Moe


2 Answers

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.

like image 183
Luke W Avatar answered Oct 19 '22 22:10

Luke W


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.

like image 26
Phil Avatar answered Oct 19 '22 22:10

Phil