Class: Ext::Settings::SettingGroup
- Extended by:
- Forwardable
- Defined in:
- lib/ext/settings.rb
Overview
This is the class that represent YourApp.settings. Do not use it directly. Kind of HashWithIndifferentAccess.
Instance Attribute Summary collapse
-
#klass ⇒ Object
readonly
To generate the YAML keys.
Instance Method Summary collapse
- #get(key) ⇒ Object (also: #[])
-
#initialize(klass) ⇒ SettingGroup
constructor
A new instance of SettingGroup.
-
#load(file) ⇒ Object
Loads your configuration file.
- #method_missing(m) ⇒ Object
-
#save(file) ⇒ Object
Exports your configuration file as YAML.
- #set(key, value, &on_change) ⇒ Object (also: #[]=)
- #to_hash ⇒ Object
- #to_yaml ⇒ Object
Constructor Details
#initialize(klass) ⇒ SettingGroup
Returns a new instance of SettingGroup.
172 173 174 175 |
# File 'lib/ext/settings.rb', line 172 def initialize(klass) @klass = klass @hash = {} end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m) ⇒ Object
190 191 192 193 |
# File 'lib/ext/settings.rb', line 190 def method_missing(m) raise NoMethodError unless @hash.has_key? m @hash[m] end |
Instance Attribute Details
#klass ⇒ Object (readonly)
To generate the YAML keys.
170 171 172 |
# File 'lib/ext/settings.rb', line 170 def klass @klass end |
Instance Method Details
#get(key) ⇒ Object Also known as: []
177 178 179 180 |
# File 'lib/ext/settings.rb', line 177 def get(key) key = convert_key(key) @hash[key] end |
#load(file) ⇒ Object
Loads your configuration file. Used by load_settings.
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/ext/settings.rb', line 196 def load(file) case file when String file = File.open(file) end vals = YAML::load(file) if vals.kind_of? Hash vals.select{|k,v| /^#{klass.name}\./ =~ k}.each do |k,v| key = k.sub /^#{klass.name}\./,'' if @hash.has_key? key @hash[key].value = v else puts "INFO: #{klass.name}.#{key} does not exist. #{@hash.inspect}" end end end end |
#save(file) ⇒ Object
Exports your configuration file as YAML. Used by save_settings.
217 218 219 220 221 222 223 224 225 |
# File 'lib/ext/settings.rb', line 217 def save(file) case file when String file = File.open(file, 'w') end file.write(to_yaml) end |
#set(key, value, &on_change) ⇒ Object Also known as: []=
183 184 185 186 187 |
# File 'lib/ext/settings.rb', line 183 def set(key, value, &on_change) key = convert_key(key) raise ArgumentError, "#{klass}.#{key} already defined" if @hash.has_key? key @hash[key] = Setting.new(klass, key, value, &on_change) end |
#to_hash ⇒ Object
227 228 229 230 231 232 |
# File 'lib/ext/settings.rb', line 227 def to_hash @hash.keys.sort.inject(Hash.new) do |hash,k| hash["#{klass}.#{k}"] = @hash[k].value hash end end |
#to_yaml ⇒ Object
234 235 236 |
# File 'lib/ext/settings.rb', line 234 def to_yaml to_hash.to_yaml end |