Class: Flexo::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/flexo/config.rb

Overview

Configuration-related functions. Able to read settings from a file, look them up, change them, and save them back to the file while the bot is running.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfig

Reads the configuration file into an array



15
16
17
18
19
20
# File 'lib/flexo/config.rb', line 15

def initialize
  @configpath = File.expand_path("~/.flexo")
  @configfile = "#{@configpath}/config.yaml"
  @config     = {}
  reload(:first)
end

Instance Attribute Details

#configfileObject (readonly) Also known as: file

Returns the value of attribute configfile.



9
10
11
# File 'lib/flexo/config.rb', line 9

def configfile
  @configfile
end

#configpathObject (readonly) Also known as: path

Returns the value of attribute configpath.



8
9
10
# File 'lib/flexo/config.rb', line 8

def configpath
  @configpath
end

Instance Method Details

#[](key) ⇒ Object

Lookup-function. Lets us use Config as an array, for convenience. so instead of Config.lookup(‘key’), we can use Config



31
32
33
34
35
36
37
# File 'lib/flexo/config.rb', line 31

def [](key)
  if @config[key]
    return @config[key]
  end

  return nil
end

#[]=(key, value) ⇒ Object

Same as [], lets you use this class as an array for saving values as well. Plugins also have access to this class, and can store their own permanent values here.

Flexo would preferably use a “namespace”, and plugins use their own namespace, using keys like core.nicks instead of just making a mess. This would also prevent collisions



46
47
48
49
# File 'lib/flexo/config.rb', line 46

def []=(key, value)
  @config[key] = value
  return @config[key]
end

#reload(first = false) ⇒ Object

Reloads configuration from file, resetting changes made since the last write.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/flexo/config.rb', line 53

def reload(first = false)
  begin
    Dir["#{@configpath}/*.yaml"].each do |file|
      tmp = YAML.load_file(file)
      next if tmp.class != Hash && tmp.class != Array
      @config.merge!(tmp)
    end
  rescue
    if first == :first
      Flexo::Logger.error "No configuration found. "
      Flexo::Logger.error "Try mkflexorc for an automated tool to help "
      Flexo::Logger.error "you create a configuration for Flexo.\n"
      exit
    else
      Flexo::Logger.warn "Configuration has disappeared! Aborting reload."
    end
  end
end

#valid?Boolean

Very basic validity-test. Just checks if we have anything stored in the configuration.

Returns:

  • (Boolean)


24
25
26
# File 'lib/flexo/config.rb', line 24

def valid?
  return !@config.empty?
end

#writeObject

Saves the current configuration to a file.



73
74
75
76
77
# File 'lib/flexo/config.rb', line 73

def write
  File.open(@configfile, 'w') do |f|
    f.puts @config.to_yaml
  end
end