Did you know that hashes can have a special proc called when a key is not found?
This could be used here very nicely.
require "backports" # Needed in Ruby 1.8.6
SETTINGS = {
"default" => {
"urls" => [],
"process?" => false,
"type" => 'Discussion'
},
"vB4Discussions" => {
"urls" => ["vB4 General Discussions"],
},
"vB4Design".downcase => {
"urls" => ["vB4 Design and Graphics Discussions"],
"type" => 'Design'
}
}
# Use defaults
SETTINGS["vb4design"].default_proc = lambda{|h, k| SETTINGS["default"][k]}
SETTINGS["vB4Discussions"].default_proc = lambda{|h, k| SETTINGS["default"][k]}
# Now the defaults are used if needed:
SETTINGS["vB4Discussions"]["type"] # ==> 'Discussion'
SETTINGS["vB4Discussions"]["process?"] # ==> false
# Defaults can be edited later:
SETTINGS["default"]["process?"] = true
SETTINGS["vB4Discussions"]["process?"] # ==> true
SETTINGS["vb4design"]["process?"] # ==> true
# Specific value can be changed too
SETTINGS["vb4design"]["process?"] = false # ==> true
SETTINGS["vB4Discussions"]["process?"] # ==> true
Note: Unless you have a valid reason to use strings, you should use symbols for your keys (i.e. :vB4Discussions
instead of "vB4Discussions"
.
The Hash.default_proc=
is new to Ruby 1.8.7, so you need to require "backports"
to use it. If you don't want this, you could instead specify the default proc when creating the hashes as follows:
DEFAULTS = {
"urls" => [],
"process?" => false,
"type" => 'Discussion'
}
SETTINGS = {
"default" => DEFAULTS,
"vB4Discussions" => Hash.new{|h, k| DEFAULTS[k]}.merge!{
"urls" => ["vB4 General Discussions"],
},
"vB4Design".downcase => Hash.new{|h, k| DEFAULTS[k]}.merge!{
"urls" => ["vB4 Design and Graphics Discussions"],
"type" => 'Design'
}
}