Class: LEnc::ConfigFile

Inherits:
Object
  • Object
show all
Defined in:
lib/lenc/config_file.rb

Overview

Manages a configuration file, which is a set of key/value pairs that can be saved to the file system.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, parentDir = nil) ⇒ ConfigFile

Returns a new instance of ConfigFile.

Parameters:

  • filename

    where configuration file is to be found (or written to, if it doesn’t yet exist)

  • parentDir (defaults to: nil)

    directory containing file; if nil, uses user’s home directory



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/lenc/config_file.rb', line 17

def initialize(filename, parentDir=nil) 
  
  parentDir ||= Dir.home
    
  @path = File.join(parentDir, filename)
  
  @content = {}
  @origContentStr = "!!!"
  if exists()
    contents = read_text_file(@path).strip
    
    @content = JSON.parse(contents)
    @origContentStr = JSON.dump(@content)
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



11
12
13
# File 'lib/lenc/config_file.rb', line 11

def path
  @path
end

Instance Method Details

#existsObject

Determine if configuration file exists on disk



34
35
36
# File 'lib/lenc/config_file.rb', line 34

def exists()
  File.exists?(@path)
end

#get_directoryObject

Get the directory containing the configuration file



39
40
41
# File 'lib/lenc/config_file.rb', line 39

def get_directory()
  File.dirname(@path)
end

#inspectObject



81
82
83
# File 'lib/lenc/config_file.rb', line 81

def inspect
  to_s
end

#remove(key) ⇒ Object

Remove key (and value), if it exists



49
50
51
# File 'lib/lenc/config_file.rb', line 49

def remove(key)
  @content.remove(key)
end

#set(key, val) ⇒ Object

Store a key => value pair (any existing value for this key is overwritten)



44
45
46
# File 'lib/lenc/config_file.rb', line 44

def set(key,val)
  @content[key] = val
end

#to_sObject



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/lenc/config_file.rb', line 69

def to_s
  s = 'ConfigFile ' 
  s << path()
  s << dh(@content)
#      " [\n"
#      @content.each_pair do |k,v|
#        s << d(k) << ' ==> ' << d(v) << "\n"
#      end
#      s << "]\n"
  s 
end

#val(key, defVal = nil) ⇒ Object

Get value for a key

Parameters:

  • defVal (defaults to: nil)

    value to return if key doesn’t exist



65
66
67
# File 'lib/lenc/config_file.rb', line 65

def val(key, defVal = nil)
  @content[key] || defVal
end

#writeObject

Write configuration file, if it has changed



54
55
56
57
58
59
60
61
# File 'lib/lenc/config_file.rb', line 54

def write
  newStr = JSON.dump(@content)

  if newStr != @origContentStr 
    @origContentStr = newStr
    write_text_file(@path,@origContentStr + "\n")
  end
end