module Twke::Conf

Public Class Methods

conf() click to toggle source
# File lib/twke/conf.rb, line 30
def conf
  @conf ||= {}
end
config_dir() click to toggle source
# File lib/twke/conf.rb, line 111
def config_dir
  File.join(ENV['HOME'], '.twke')
end
config_file() click to toggle source
# File lib/twke/conf.rb, line 115
def config_file
  File.join(config_dir, 'config.yml')
end
exists?(varname) click to toggle source
# File lib/twke/conf.rb, line 49
def exists?(varname)
  conf.has_key?(varname)
end
get(varname) click to toggle source
# File lib/twke/conf.rb, line 45
def get(varname)
  conf[varname.to_s]
end
list(varpfx) click to toggle source

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
# 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
load() click to toggle source
# 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
save() click to toggle source

Files are saved atomically.

# 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) click to toggle source

Everytime a value is modified the config DB is written

# 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