Hey Ben-
Here is a model I use for settings and stuff like you are talking about. I wanted to be able to edit my configs in the interface so I store it in a model but it has an interface like a hash:
class DbHash < ActiveRecord::Base
class << self
def (key)
pair = find_by_key(key.to_s)
pair.value unless pair.nil?
end
def =(key, value)
pair = find_by_key(key)
unless pair
pair = new
pair.key, pair.value = key.to_s, value
pair.save
else
pair.value = value
pair.save
end
value
end
def to_hash
Hash[ *find_all.map { |pair| [pair.key, pair.value] }.flatten ]
end
end
end
create_table "configurations", :force => true do |t|
t.column "key", :string, :limit => 40, :default => "", :null => false
t.column "value", :string, :default => ""
end
Cheers-
-Ezra
An alternative approach that we’ve tried in a couple of our apps is to extend Rails::Configuration to add our own settings. The nice thing about this approach is it lets us easily have different settings for different environments, with defaults and everything, just like the built in rails configuration options, and all checked in to svn. The downside is that we haven’t been able to figure out a way to do it without creating a global reference to the config object, which creates some awkward coupling between the config and whatever uses it, such as model objects. Its pretty easy to do, though.
in environment.rb:
class MyConfig < Rails::Configuration
#define attributes or whatever
end
MY_CONFIG = MyConfig.new
Rails::Initializer(:process, MY_CONFIG) do |config|
#all the usual config stuff
config.my_custom_setting = “default value”
end
Then wherever you need the configuration value, you can check it:
def some_method
filename = MY_CONFIG.my_custom_setting
end
We also tried a more dependency injection based approach, where the config object would set values for the classes that needed them. We ran into problems when classes are reloaded in development mode, though - everything would work fine on the first request, but on subsequent requests the class would have been reloaded, losing the values that had been set before, but the environment code does not get re-run so we would end up not having the values set at all.
Just an idea, and Ezra’s approach will certainly work great for storing the values in the database.
-Steve Holder
http://wiki.rubyonrails.org/rails/pages/SettingsPlugin
Very easy to use. Can be used to setup user specific settings, as
well as applicatoin-wide settings. Since the settings are in the db
you can change setting without restarting the app, as you would have
to if they were in environment.rb.