class ConfigStruct
the Configstruct object inherits from OpenStruct and adds some features:
-
set default values
-
redirects output and input IO to custom streams
-
writes file on disk as yaml
Public Class Methods
new(options = nil, input = STDIN, output = STDOUT, unless_set = false)
click to toggle source
creates new object
Calls superclass method
# File lib/configstruct.rb, line 12 def initialize(options = nil, input = STDIN, output = STDOUT, unless_set = false) super(options) @input = input @output = output @unless_set = unless_set set_defaults prepare_dirs addvalues end
Public Instance Methods
addvalues()
click to toggle source
adds value in the configuration hash
# File lib/configstruct.rb, line 34 def addvalues setup unless File.exist? self.basefile YAML.load_file(self.basefile).each do |k, v| unless @unless_set && defined? self[v] new_ostruct_member(k) send("#{k}=", v) end end end
default(var, value)
click to toggle source
attributes value if it is nil
# File lib/configstruct.rb, line 50 def default(var, value) send(var).nil? && send("#{var}=", value) end
gets(*args)
click to toggle source
redirect gets fromm the initialized input
# File lib/configstruct.rb, line 77 def gets(*args) @input.gets *args end
prepare_dirs()
click to toggle source
creates dir where to store config if it does not exist
# File lib/configstruct.rb, line 29 def prepare_dirs FileUtils.mkdir_p self.basedir unless Dir.exist? self.basedir end
print(*string)
click to toggle source
redirect print to the initialized output
# File lib/configstruct.rb, line 67 def print(*string) @output.print *string end
printf(string, *args)
click to toggle source
redirect printf to the initialized output
# File lib/configstruct.rb, line 72 def printf(string, *args) @output.printf string, *args end
puts(*string)
click to toggle source
redirect puts to the initialized output
# File lib/configstruct.rb, line 62 def puts(*string) @output.puts *string end
set_defaults()
click to toggle source
sets defaults value for initializer
# File lib/configstruct.rb, line 23 def set_defaults default :basedir, '/tmp' default :basefile, File.join(self.basedir, 'config.yml') end
setup()
click to toggle source
creates a blank config file with empty values
# File lib/configstruct.rb, line 45 def setup write Hash.new end
write(values)
click to toggle source
writes config faile on disk as yaml
# File lib/configstruct.rb, line 55 def write(values) File.open(self.basefile, 'w') do |f| f.write YAML.dump(values) end end