Class: Conf

Inherits:
Hash show all
Defined in:
lib/tkxxs/conf.rb

Overview

Keywords: ,configuration ,ini ,preferences ,setup Helps storing and managing configuration data. At present, uses YAML-files to store the data.

Important methods:

Conf.new
Conf#filename   Returns the full path of file, where Conf is saved 
Conf#section= section   section must be String, Integer, Float or nil, _not_ a Symbol
Conf#or_default(key, defaultValue)  
Conf#[key]= value   key must be a Symbol or String
Conf#[key]   Returns the stored value
Conf#save   Writes Conf to file
Conf#instant_save = true/false: switches on save to file for every change of Conf

Having keys and section of the same type and value is no problem.

Example usage:

require 'axel/conf'
CONF = Conf.new  # Filename for storing CONF can be given as attribute;

class MyClass

  def initialize(  )
    CONF.section = "my_section_1" # Optional, default is provided
    # Defines a section (hash key) where to read and store data
    p x = CONF.or_default( :x, 123 ) 
    # If run the first time, usually Conf["my_section"][:x] is not set to any value.
    # If Conf["my_section"][:x] is not set to any value, sets x to 123,
    # stores 123 in Conf["my_section"][:x] and saves it to the conf-File.
    # If run the next time, Conf["my_section"][:x] is already set to a value
    # and x is set to the value of Conf["my_section"][:x]

    p @y = CONF.or_default( :@y, "abc" )

    puts "Config-File is: " + CONF.filename
    myMethod(x)
  end # initialize

  def myMethod( x )
    x = x*x
    @y = "new_y"

    CONF[:x] = x  # sets Conf["my_section"][:x] to the new value of x
    CONF[:@y] = @y
    puts "CONF[:x] is " + CONF[:x].inspect
    puts "CONF[:@y] is " + CONF[:@y].inspect

    CONF.save # saves the content of Conf.
  end # myMethod

end # MyClass

klass = MyClass.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Hash

#dup2!

Constructor Details

#initialize(configFileDNE = Conf.filename_proposal) ⇒ Conf

Attributes: configFileDNE: path including filename and fileextension



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/tkxxs/conf.rb', line 96

def initialize( configFileDNE=Conf.filename_proposal )
#p :xxx
  raise unless configFileDNE
  @configFileDNE = configFileDNE.dup.strip.gsub('\\', '/')
  @instant_save = false
  @section = nil
  
  if File.file?( @configFileDNE )
    dataFromFile = read
    self.replace( dataFromFile )  if dataFromFile
  end
#exit
  self.section = nil  unless self.has_key?(nil) # section "nil" always needed

  super()
  save()  # writeable?
end

Instance Attribute Details

#instant_saveObject

Returns the value of attribute instant_save.



92
93
94
# File 'lib/tkxxs/conf.rb', line 92

def instant_save
  @instant_save
end

#sectionObject

Returns the value of attribute section.



93
94
95
# File 'lib/tkxxs/conf.rb', line 93

def section
  @section
end

Class Method Details

.dirObject

From: Joel VanderWerf: “preferences-0.3.0”. Utility method for guessing a suitable directory to store preferences. On win32, tries APPDATA, USERPROFILE, and HOME. On other platforms, tries HOME and ~. Raises EnvError if preferences dir cannot be chosen. Not called by any of the Preferences library code, but available to the client code for constructing an argument to Preferences.new.

Some modifications by Axel



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/tkxxs/conf.rb', line 233

def Conf.dir
    case Platform::OS.to_s.downcase
    when 'win32'
      dir = 
        ENV['APPDATA'] ||  # C:\Documents and Settings\name\Application Data
        ENV['USERPROFILE'] || # C:\Documents and Settings\name
        ENV['HOME']
    else
      dir =
        ENV['HOME'] ||
        File.expand_path('~')
    end

    unless dir
      raise EnvError, "Can't determine a configuration directory."
    end
  dir = dir.gsub('\\', '/')
  dir
end

.filename_proposal(extension = '.cfg') ⇒ Object

Conf.dir



253
254
255
256
257
# File 'lib/tkxxs/conf.rb', line 253

def Conf.filename_proposal( extension='.cfg' )
  fileN = File.basename( $0, File.extname($0) )
  configFileDNE = File.join( Conf.dir, fileN, fileN + extension.to_s)
  configFileDNE
end

Instance Method Details

#[](key) ⇒ Object

Returns the value corresponding to key, while Config is pointing to the section set by Conf::section= . Attributes: key: Symbol or String



135
136
137
138
139
140
141
# File 'lib/tkxxs/conf.rb', line 135

def []( key )
  raise "Key must be a Symbol or String" unless key.is_a?( Symbol )  ||  key.is_a?( String )

  res = self.of(@section)[key]
  res = res.dup?  ?  res.dup  :  res
  res
end

#[]=(key, value) ⇒ Object

Sets the value for a corresponding key. If key does not exist, it will be created. Attributes: key: Symbol or String; value



146
147
148
149
150
151
152
# File 'lib/tkxxs/conf.rb', line 146

def []=( key, value )
  raise "key must be a Symbol or String" unless key.is_a?( Symbol )  ||  key.is_a?( String )

  self.of(@section).store( key, value)
  self.save  if @instant_save
  value
end

#deleteObject

Deletes the config-File and clears all data of Conf.



218
219
220
221
222
# File 'lib/tkxxs/conf.rb', line 218

def delete(  )
  File.delete(@configFileDNE)
  self.clear
  self
end

#delete_conf_fileObject

initialize



114
115
116
# File 'lib/tkxxs/conf.rb', line 114

def delete_conf_file(  )
  File.delete( @configFileDNE )
end

#filenameObject

Returns the filename of the config file



128
129
130
# File 'lib/tkxxs/conf.rb', line 128

def filename(  )
  @configFileDNE
end

#ofObject



89
# File 'lib/tkxxs/conf.rb', line 89

alias of []

#or_default(key, defaultValue) ⇒ Object

If key is not an existing key, key will be created with value = defaultValue and saves it to the config-File. Returns defaultValue.

If key is an exsiting key, the correspondig value will be returned.



159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/tkxxs/conf.rb', line 159

def or_default( key, defaultValue )
  raise "key must be a Symbol or String" unless key.is_a?( Symbol )  ||  key.is_a?( String )

  if self.of(@section).has_key?( key ) # ToDo: Nicer: create Conf::has_key?
    res = self[key]
  else
    self[key]= defaultValue
    res = defaultValue
    self.save  ## if @instant_save # 2009-06-11
  end

  res
end

#orig_to_hashObject



90
# File 'lib/tkxxs/conf.rb', line 90

alias orig_to_hash to_hash

#readObject

section=



189
190
191
192
193
194
195
196
# File 'lib/tkxxs/conf.rb', line 189

def read()
  FileUtils.mkpath( File.dirname( @configFileDNE ) )
  # Ruby 1.8.7 cannot read psych-formated YAML-Files. As of 2013-03-15, Ruby
  # 1.8.7 and 1.9 can read syck-formated YAML Files. For compatibility, I
  # choose syck-format.
  YAML::ENGINE.yamler = "syck"  if YAML.const_defined?( :ENGINE )
  File.open( @configFileDNE ) { |f|   YAML.load(f)  }
end

#saveObject

def save()

FileUtils.mkpath( File.dirname( @configFileDNE ) )
File.open( @configFileDNE, "w" ) { |f|    YAML.dump(self, f)   }

end



203
204
205
206
207
208
209
210
211
212
213
# File 'lib/tkxxs/conf.rb', line 203

def save()
  FileUtils.mkpath( File.dirname( @configFileDNE ) )
  YAML::ENGINE.yamler = "syck"   if YAML.const_defined?( :ENGINE )
  File.open( @configFileDNE, "w" ) { |f|    YAML.dump(self, f)   }
  # I write a 2nd File in psych-format in case syck is not longer available
  # sometimes.
  if YAML.const_defined?( :ENGINE )
    YAML::ENGINE.yamler = "psych"
    File.open( @configFileDNE + '_psy', "w" ) { |f|    YAML.dump(self, f)   }
  end
end

#to_hashObject

delete_conf_file



118
119
120
121
122
123
124
# File 'lib/tkxxs/conf.rb', line 118

def to_hash(  )
  h = Hash.new
  self.each {|key, val|  
    h[key] =  val.dup  ?  val.dup  : val
  }
  h
end