Class: Config
- Inherits:
-
Object
- Object
- Config
- Defined in:
- lib/config.rb
Instance Method Summary collapse
- #init_configs ⇒ Object
-
#initialize(options = {}) ⇒ Config
constructor
A new instance of Config.
- #load_cfg(file) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Config
Returns a new instance of Config.
4 5 6 7 8 |
# File 'lib/config.rb', line 4 def initialize( = {}) filepath = [:file] || 'autoexec.cfg' init_configs load_cfg(filepath) end |
Instance Method Details
#init_configs ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/config.rb', line 10 def init_configs @configs = { password: { help: 'Password to the server', default: '' } } @commands = { echo: { help: 'Echo the text', callback: proc { |arg| puts arg } }, quit: { help: 'Quit', callback: proc { |_| exit } } } @configs.each do |cfg, data| self.class.send(:attr_accessor, cfg) instance_variable_set("@#{cfg}", data[:default]) end end |
#load_cfg(file) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/config.rb', line 24 def load_cfg(file) return unless File.exist?(file) File.readlines(file).each_with_index do |line, line_num| line.strip! next if line.start_with? '#' next if line.empty? words = line.split cmd = words.shift.to_sym arg = words.join(' ') if @configs[cmd] instance_variable_set("@#{cmd}", arg) elsif @commands[cmd] @commands[cmd][:callback].call(arg) else puts "Warning: unsupported config '#{cmd}' #{file}:#{line_num}" end end end |