Class: ConfigStruct

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/configstruct.rb

Overview

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

Instance Method Summary collapse

Constructor Details

#initialize(options = nil, input = STDIN, output = STDOUT, unless_set = false) ⇒ ConfigStruct

creates new object



12
13
14
15
16
17
18
19
20
# 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

Instance Method Details

#addvaluesObject

adds value in the configuration hash



34
35
36
37
38
39
40
41
42
# 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) ⇒ Object

attributes value if it is nil



50
51
52
# File 'lib/configstruct.rb', line 50

def default(var, value)
  send(var).nil? && send("#{var}=", value)
end

#gets(*args) ⇒ Object

redirect gets fromm the initialized input



77
78
79
# File 'lib/configstruct.rb', line 77

def gets(*args)
  @input.gets *args
end

#prepare_dirsObject

creates dir where to store config if it does not exist



29
30
31
# File 'lib/configstruct.rb', line 29

def prepare_dirs
  FileUtils.mkdir_p self.basedir unless Dir.exist? self.basedir
end

redirect print to the initialized output



67
68
69
# File 'lib/configstruct.rb', line 67

def print(*string)
  @output.print *string
end

#printf(string, *args) ⇒ Object

redirect printf to the initialized output



72
73
74
# File 'lib/configstruct.rb', line 72

def printf(string, *args)
  @output.printf string, *args
end

#puts(*string) ⇒ Object

redirect puts to the initialized output



62
63
64
# File 'lib/configstruct.rb', line 62

def puts(*string)
  @output.puts *string
end

#set_defaultsObject

sets defaults value for initializer



23
24
25
26
# File 'lib/configstruct.rb', line 23

def set_defaults
  default :basedir, '/tmp'
  default :basefile, File.join(self.basedir, 'config.yml')
end

#setupObject

creates a blank config file with empty values



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

def setup
  write Hash.new
end

#write(values) ⇒ Object

writes config faile on disk as yaml



55
56
57
58
59
# File 'lib/configstruct.rb', line 55

def write(values)
  File.open(self.basefile, 'w') do |f|
    f.write YAML.dump(values)
  end
end