Module: Twke::Conf

Defined in:
lib/twke/conf.rb

Class Method Summary collapse

Class Method Details

.confObject



30
31
32
# File 'lib/twke/conf.rb', line 30

def conf
  @conf ||= {}
end

.config_dirObject



111
112
113
# File 'lib/twke/conf.rb', line 111

def config_dir
  File.join(ENV['HOME'], '.twke')
end

.config_fileObject



115
116
117
# File 'lib/twke/conf.rb', line 115

def config_file
  File.join(config_dir, 'config.yml')
end

.exists?(varname) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/twke/conf.rb', line 49

def exists?(varname)
  conf.has_key?(varname)
end

.get(varname) ⇒ Object



45
46
47
# File 'lib/twke/conf.rb', line 45

def get(varname)
  conf[varname.to_s]
end

.list(varpfx) ⇒ Object

This will return a list of the unique commands that begin with the varpfx prefix assumed to be a sub-command prefix.

For example, assume the following variables are set:

net.tcp.foobar => 1
net.tcp.barbar => 2

So:

list('net.tcp') would return: ["barbar", "foobar"]
list('net') would return: ["tcp"]

list('net.tc') would return: []
     Because there are no sub-commands with 'net.tc.' as
     their prefix


70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/twke/conf.rb', line 70

def list(varpfx)
  # Strip leading/trailing periods
  varpfx = varpfx[1, varpfx.length] if varpfx =~ /^\./
  varpfx = varpfx[0, varpfx.length - 1] if varpfx =~ /\.$/

  # XXX: Really need a tree structure to do this efficiently
  conf.keys.inject([]) do |ar, k|
    if k =~ /^#{varpfx}\./
      ar << k.gsub(/^#{varpfx}\./, '').split(".")[0]
    end
    ar
  end.sort.uniq
end

.loadObject



84
85
86
87
88
89
90
91
92
93
# File 'lib/twke/conf.rb', line 84

def load
  begin
    yml = YAML.load_file(config_file)
    @conf = yml
  rescue Errno::ENOENT => err
    @conf = {}
  rescue => err
    raise "Unknown error reading config file: #{err.message}"
  end
end

.saveObject

Files are saved atomically.



98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/twke/conf.rb', line 98

def save
  unless File.exist?(config_dir)
    FileUtils.mkdir_p(config_dir, :mode => 0700)
  end

  tmpfile = File.join(config_dir, "tmpconfig_#{rand 999999}")
  File.open(tmpfile, "w") do |f|
    YAML.dump(conf, f )
  end

  FileUtils.mv(tmpfile, config_file)
end

.set(varname, value) ⇒ Object

Everytime a value is modified the config DB is written



35
36
37
38
39
40
41
42
43
# File 'lib/twke/conf.rb', line 35

def set(varname, value)
  if varname =~ /^\./ || varname =~ /\.$/ || varname.length == 0
    raise "Invalid variable name"
  end

  conf[varname.to_s] = value

  save
end