Class: ConfModifier
- Inherits:
-
Object
- Object
- ConfModifier
- Defined in:
- lib/common/socket/conf_modifier.rb,
lib/common/socket/rlib/conf_modifier.rb
Overview
This class supply conf modification related service e.g. modify single/batch conf items
- Author
-
chenjie
- Data
-
2009-4-30
Instance Method Summary collapse
-
#get_conf(key) ⇒ Object
获取某个配置项的值.
-
#initialize(confPath) ⇒ ConfModifier
constructor
A new instance of ConfModifier.
-
#modify(key, newValue) ⇒ Object
修改单个配置项.
-
#modifyall(hash) ⇒ Object
批量修改配置项.
-
#writeconf ⇒ Object
按顺序回写配置文件.
Constructor Details
#initialize(confPath) ⇒ ConfModifier
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/common/socket/conf_modifier.rb', line 13 def initialize(confPath) @confPath = confPath #lineNum : key @dic= Hash.new #key : value @conf = Hash.new file = File.open(@confPath) cnt = 0 file.each{ |line| #print line cnt+=1 if line.strip[0, 1] == '#' or line.strip.length == 0 @dic[ cnt ] = line.strip else list = line.strip.split(":") key = list[0].strip if list[1] != nil then list.delete_at(0) value = list.join(":").strip else #只有key没有value的情况 value = '' end @dic[ cnt ] = key @conf[key] = value end } @lines = cnt file.close end |
Instance Method Details
#get_conf(key) ⇒ Object
获取某个配置项的值
112 113 114 |
# File 'lib/common/socket/conf_modifier.rb', line 112 def get_conf(key) return @conf[key] end |
#modify(key, newValue) ⇒ Object
修改单个配置项
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/common/socket/conf_modifier.rb', line 55 def modify(key, newValue) if @conf.has_key?(key) puts "modify from [" + key + "=>" + @conf[key] + "] to [" + key + "=>" + newValue + " ]" @conf[key] = newValue else puts "add new conf " + key + "=>" + newValue @lines += 1 @dic[@lines] = key @conf[key] = newValue end end |
#modifyall(hash) ⇒ Object
批量修改配置项
73 74 75 76 77 78 79 |
# File 'lib/common/socket/conf_modifier.rb', line 73 def modifyall(hash) if hash != nil then hash.each{|key,value| modify(key, value) } end end |
#writeconf ⇒ Object
按顺序回写配置文件
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/common/socket/conf_modifier.rb', line 88 def writeconf file = File.open(@confPath, 'w') @dic.sort_by { |key, value| key } @dic.each_key { |ki| if @dic[ki].strip.length != 0 #key, value if @conf.has_key?(@dic[ki]) file.print(@dic[ki] , " : ",@conf[@dic[ki]] , "\n") else file.print( @dic[ki] , "\n") end else file.print( "\n") end } file.close end |