Class: Kstarv::KV

Inherits:
Object
  • Object
show all
Defined in:
lib/kstarv/k_v.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, join = '=') ⇒ KV

Returns a new instance of KV.



10
11
12
13
14
15
16
# File 'lib/kstarv/k_v.rb', line 10

def initialize file, join='='
  @case ||= true
  @file = file
  @join = join
  @instance_vars  = []
  load_attr
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arg) ⇒ Object



46
47
48
49
50
51
# File 'lib/kstarv/k_v.rb', line 46

def method_missing name, *arg
  # name: _ipaddr=_
  # if name =~ /[\w]+=$/
  v = arg.first ?  arg.first : ''
  create_attr [name.to_s.split('=')[0], v]
end

Instance Attribute Details

#caseObject

set key downcase or upcase downcase and @case is true by default



8
9
10
# File 'lib/kstarv/k_v.rb', line 8

def case
  @case
end

Instance Method Details

#load_attrObject



36
37
38
39
40
41
42
43
44
# File 'lib/kstarv/k_v.rb', line 36

def load_attr
  File.open(@file) do |f|
	f.each do |line|
	  # remove blank line
	  # remove beginning and end space
	  create_attr(line.strip.split(@join)) if line.gsub("\n",'').length != 0 && !(line.strip =~ /^#/)
	end
  end
end

#to_sObject



53
54
55
# File 'lib/kstarv/k_v.rb', line 53

def to_s
  @str ||= File.read(@file)
end

#writeObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/kstarv/k_v.rb', line 20

def write
  kvs = @instance_vars.map do | var |
	"#{convert_case(var)}=#{instance_var_get(var)}"
  end
  # kvs =>  [ "DEVICE=eth0", "HWADDR=00:1E:67:24:E8:2D", "TYPE=Ethernet" ...]

  # r+是覆盖写,w+是清除后写,a+是追加写
  File.open(@file, 'w+') do |f|
	kvs.map do |kv|
	  f.write(kv)
	  f.puts
	end
  end
end