Sunday, April 16, 2006

App Wide settings

We recently played a card which read something along these lines - 'As a user of this system I should be able to set some application settings in the database'

Till date we had kept all the 'settings' (for the lack of a better word) in a module and we were using it off the module.
module Prefs
BASE_DIR='blah'
REMOTE_SERVER='blah blah'
...
end
usage in the code was
  Prefs::BASE_DIR
Had not heard about this Settings plugin by Alex Wayne, but I think we came up with a simpler solution using the 'const_missing' on an object. The Settings plugin uses 'method_missing' to do pretty much the same, but it needed constants to be called like this - Prefs.constant(which I feel is confusing) rather than Prefs::CONSTANT.
module Prefs
def self.const_missing(constant)
const_set(constant, Preference.value(constant))
end
end
So basically whenever we access a constant on Prefs (like Prefs::BASE_DIR) the const_missing is triggered and we dip into the Preference table to fetch the constant and set it on Prefs.

So a bunch of hardcoded constants were easily turned into a few lines of code that fetched the information from the database. And the best part was that we did not have to go and change the way we access constants all over the code.

0 Comments:

Post a Comment

<< Home