Class: Toga::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/toga/config.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Config

Returns a new instance of Config.



7
8
9
10
11
12
# File 'lib/toga/config.rb', line 7

def initialize(path)
  self.data = {}
  @path = path
  
  read!
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/toga/config.rb', line 47

def method_missing(*args)
  name = args.shift.to_s
  
  # Setter
  if name[name.length-1] == "="
    attribute = name.gsub(/[^A-z_]+/, '').to_sym
    self.data[attribute] = args.first.strip
    self.save!
    return self.data[attribute]
  end
  
  # Getter
  name = name.to_sym
  return @data[name].strip if @data.has_key?(name)
  
  nil
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



4
5
6
# File 'lib/toga/config.rb', line 4

def data
  @data
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'lib/toga/config.rb', line 5

def path
  @path
end

Class Method Details

.load!Object



14
15
16
17
# File 'lib/toga/config.rb', line 14

def self.load!
  f = File.join(Dir.getwd, Toga::CONFIGFILE_NAME)
  self.new(f)
end

Instance Method Details

#read!Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/toga/config.rb', line 19

def read!
  begin
    handle = File.open(@path, 'r')
  rescue
    # File doesn't exist yet
    File.open(@path, 'w') {}
    return
  end
  
  handle.each do |l|
    pair = l.split('=')
    key = pair.first
    value = pair.last
    if key.nil? or key.strip.empty? or value.nil? or value.strip.empty?
      next
    end
    self.data[key.to_sym] = value.strip
  end
end

#save!Object



39
40
41
42
43
44
45
# File 'lib/toga/config.rb', line 39

def save!
  File.open(@path, 'w') do |l|
    self.data.each do |key, value|
      l.puts "#{key}=#{value}"
    end
  end
end