module Buryspam::Config::Converter

Try to convert values (strings read from a configuration file, for example), to the appropriate type. In all these methods attrib is the name of the configuration parameter attribute that is being set (e.g., word_file).

Constants

IEC_PREFIX
SI_PREFIX

Convert the SI/IEC suffix to numbers. This allows strings such as "10MiB" to be used for file sizes.

Public Class Methods

boolean(attrib, value) click to toggle source

Convert value string to a boolean.

  • Valid true values are: true, yes, on.

  • Valid false values are: false, no, off.

# File buryspam.rb, line 2708
def boolean(attrib, value)
  return value if value == false || value == true
  case value
    when "true", "yes", "on"  then true
    when "false", "no", "off" then false
    else raise Error, "Invalid boolean value: '#{value}'"
  end
end
byte_suffix(units) click to toggle source
# File buryspam.rb, line 2744
def byte_suffix(units)
  return 1 if units.nil? || units.empty?
  if idx = SI_PREFIX.index(units)
    return 1000**(idx+1)
  elsif idx = IEC_PREFIX.index(units)
    return 1024**(idx+1)
  end
  raise Error, "Invalid byte suffix: #{units}"
end
date_rng(attrib, value) click to toggle source

Convert the value parameter to a DateRange. See the DateRange class for more details.

# File buryspam.rb, line 2566
def date_rng(attrib, value)
  DateRange.new(value) rescue
    raise Error, $!.message
end
dir(attrib, value) click to toggle source

If value is already an absolute directory name or can be ~-expanded, then return the (expanded) value. If value is not absolute, then prepend the directory of the word_file so as to keep all buryspam generated files (e.g., cache, logs) in the same place. The full pathname is returned. An exception is raised if we can't determine a full pathname.

# File buryspam.rb, line 2625
def dir(attrib, value)
  return value                   if FileUtils.dir_absolute?(value)
  return File.expand_path(value) if value.strip[0] == ~~

  # Prepend the word_file dirname if value is not absolute.
  word_file = Config.config[:word_file].value ||
              Config.config[:word_file].dflt_value || ""
  dir = File.join(File.dirname(word_file), value)
  return dir if FileUtils.dir_absolute?(dir)

  # If still not absolute, then we have a problem.
  raise Error, "Directory not absolute: '#{value}'\n" +
        "    (Specify the full pathname" +
        (attrib == :word_file ? ".)" :
                   " or set the 'word_file' parameter first.)")
end
dirs(attrib, value) click to toggle source

Converts a comma separated list of directory strings (value) into an array of absolute directory name strings. (Uses the directory of the word_file for any relative directory names in the list, if necessary.) The array of directories are returned.

# File buryspam.rb, line 2646
def dirs(attrib, value)
  errs = []
  names = value.split(/\s*,\s*/).map { |d|
    begin
      dir(attrib, d)
    rescue Error
      errs << $!.message
      nil
    end
  }.compact.uniq
  valid = names.find_all { |d| File.directory?(d) }
  invalid = names - valid
  if ! invalid.empty?
    s = invalid.size == 1 ? "y" : "ies"
    errs << "Nonexistent director#{s}:\n    " + invalid.join("\n    ")
  end
  if valid.empty?
    errs << "No valid directories given."
  end
  raise Error, errs.join("\n  ") unless errs.empty?
  valid
end
file(attrib, value) click to toggle source

Convert value to a string representing the full pathname of a file. If value does not represent an absolute filename, then it is relative to the word_file directory. Make sure the file's directory exists before returning the filename.

# File buryspam.rb, line 2545
def file(attrib, value)
  # An empty/nil value may mean a file is not used by default.
  return "" if value.nil? || value.strip.empty?
  val = dir(attrib, value)
  FileUtils.ensure_dir_exists(File.dirname(val))
  if File.exist?(val) && ! File.file?(val)
    raise Error, "'#{val}' is not a file."
  end
  val
end
float(attrib, value) click to toggle source

If value isn't already a Float, then convert a string value the form "\d+.\d+" to a Float.

# File buryspam.rb, line 2597
def float(attrib, value)
  unless value.kind_of?(Float) || /^-?\d+\.\d+$/.match(value)
    raise Error, "Invalid floating point number: '#{value}'"
  end
  value.to_f
end
float_rng(attrib, value) click to toggle source

If value isn't already a range of Floats, then convert a string value of the form "<float>..<float>" to a range of Floats.

# File buryspam.rb, line 2606
def float_rng(attrib, value)
  if value.class == Range &&
     value.first.kind_of?(Float) &&
     value.last.kind_of?(Float)
    value
  else
    unless /^(\d+\.\d+)\.\.(\d+\.\d+)$/.match(value)
      raise Error, "Invalid floating point number range: '#{value}'"
    end
    Range.new($1.to_f, $2.to_f)
  end
end
int(attrib, value) click to toggle source

If value isn't already an Integer, then convert a string value of the form "\d+" to a range of Integers.

# File buryspam.rb, line 2573
def int(attrib, value)
  unless value.kind_of?(Integer) || /^-?\d+$/.match(value)
    raise Error, "Invalid integer: '#{value}'"
  end
  value.to_i
end
int_rng(attrib, value) click to toggle source

If value isn't already a range of Integers, then convert a string value of the form "<int>..<int>" to a range of Integers.

# File buryspam.rb, line 2582
def int_rng(attrib, value)
  if value.class == Range &&
     value.first.kind_of?(Integer) &&
     value.last.kind_of?(Integer)
    value
  else
    unless /^(\d+)\.\.(\d+)$/.match(value)
      raise Error, "Invalid integer range: '#{value}'"
    end
    Range.new($1.to_i, $2.to_i)
  end
end
level(attrib, value) click to toggle source

Convert the string value to a log level. value must be one of debug, info, warn, error, fatal or unknown (see Logger::Severity).

# File buryspam.rb, line 2720
def level(attrib, value)
  begin
    # Map a string log level (e.g. "debug") to a constant value
    # in the Severity module of the Logger class.
    Logger::Severity.const_get(value.upcase.to_sym)
  rescue NameError
    raise Error, "Invalid log level: '#{value}'.\n    " +
               "(Valid levels: #{Logger::LEVELS.join(", ")})"
  end
end
regex(attrib, value) click to toggle source

Converts value as follows:

  • If value is already a Regexp, then return it.

  • If value is nil or an empty string, then return an empty string. The empty string will be converted to nil (a 'regular expression' that matches nothing when used as nil =~ string).

  • Otherwise, convert a string of the form "/.../" to a Regexp. An empty regular expression, "//", matches everything.

# File buryspam.rb, line 2686
def regex(attrib, value)
  return value if value.class == Regexp
  return nil   if value.nil? || value.empty?    # Match nothing.
  if %r{^/(.*)/([ixm]*)$}.match(value)
    pattern, options = $1, $2
    opts  = 0
    opts |= Regexp::EXTENDED      if /x/.match(options)
    opts |= Regexp::MULTILINE     if /m/.match(options)
    opts |= Regexp::IGNORECASE    if /i/.match(options)
    begin
      return Regexp.new(pattern, opts)
    rescue RegexpError
      raise Error, $!.message
    end
  end

  raise Error, "Invalid regular expression '#{value}'"
end
size(attrib, value) click to toggle source

If value is an Integer, then simply return it. If it is of the form "\d+<suffix>", then use suffix as an SI/IEC suffix to determine the actual numeric size.

# File buryspam.rb, line 2672
def size(attrib, value)
  return value                           if value.kind_of?(Integer)
  return $1.to_i * byte_suffix($2) if /^([\d_]+)(.*)$/.match(value)
  raise Error, "Invalid size '#{value}'"
end
store(attrib, value_str) click to toggle source

Parse, validate and store the given configuration parameter's value. Raise errors if the parameter name is unknown or there are problems during the parsing/validation. Notify user of duplicate parameter settings. attrib is the name of the parameter and value_str is the attribute's value in string form as obtained from the configuration file/command line.

# File buryspam.rb, line 2522
def store(attrib, value_str)
  param = Config.config[attrib]
  raise Error, "Unknown parameter: '#{attrib}'" if param.nil?
  old_value = param.value
  param.value = send(param.typ, attrib, value_str)
  validate(attrib, param)
  if param.init && old_value != param.value
    Status.warn("Overriding '#{attrib}' parameter:\n" +
      " '#{old_value}' =>\n  '#{param.value}'")
  else
    param.init = true
  end
end
str(attrib, value) click to toggle source

Convert the value parameter to a string.

# File buryspam.rb, line 2537
def str(attrib, value)
  value.to_s
end
timer(attrib, value) click to toggle source

A time interval during which an event should happen (e.g., polling the IMAP server). See Timer class for valid timer values.

# File buryspam.rb, line 2559
def timer(attrib, value)
  Timer.new(value) rescue
    raise Error, $!.message
end
validate(attribute, param) click to toggle source

Test the configuration parameter's value using its validation method (both stored in param). Raise an exception if it fails the validation. attribute is the name of the configuration parameter.

# File buryspam.rb, line 2734
def validate(attribute, param)
  if param.validate && ! param.validate.call(param.value)
    raise Error, "'#{attribute}' #{param.error_msg}."
  end
end