Class: PythonConfig::ConfigParser

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

Overview

This is the main class that handles configurations. You parse, modify, and output through this class. See the README for tons of examples.

Constant Summary collapse

SECTION_REGEXP =
/\[([^\[\]]*)\]/
ASSIGNMENT_REGEXP =
/([^:=\s]+)\s*[:=]\s*([^\n]*?)$/
LONG_HEADER_REGEXP =
/^([ \t]+)([^\n]+)$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io = nil) ⇒ ConfigParser

Creates a new ConfigParser. If io is provided, the configuraiton file is read from the io.



64
65
66
67
68
69
# File 'lib/pythonconfig.rb', line 64

def initialize(io = nil)
  @sections = {}
  io.each do |line|
    parse_line line
  end unless io.nil?
end

Instance Attribute Details

#sectionsObject (readonly)

Returns the value of attribute sections.



57
58
59
# File 'lib/pythonconfig.rb', line 57

def sections
  @sections
end

Instance Method Details

#[](section) ⇒ Object

Returns the section given by section



102
103
104
# File 'lib/pythonconfig.rb', line 102

def [](section)
  @sections[section]
end

#add_section(section_name, values = {}) ⇒ Object

Creates a new section, with the values as provided by the (optional) values parameter



90
91
92
93
94
95
96
97
98
99
# File 'lib/pythonconfig.rb', line 90

def add_section(section_name, values={})
  newsection = ConfigSection.new(values)
  @sections[section_name] = newsection
  self.instance_eval %Q{
    def #{section_name.downcase}
      @sections["#{section_name}"]
    end
  }
  newsection
end

#parse_line(line) ⇒ Object

:nodoc:



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/pythonconfig.rb', line 71

def parse_line line #:nodoc:

  if line =~ SECTION_REGEXP
    section_name = $1
    @cursection = add_section section_name
  elsif line =~ ASSIGNMENT_REGEXP
    @cursection[$1] = $2
    @cur_assignment = $1
  elsif line =~ LONG_HEADER_REGEXP
    @cursection[@cur_assignment] += " " + $2
  end
end

#section_namesObject

Returns the names of all the sections, which can be used for keys into the sections



85
86
87
# File 'lib/pythonconfig.rb', line 85

def section_names
  @sections.keys
end

#to_sObject

Returns the configuration as a string that can be output to a file. Does not perform interpolation before writing.



108
109
110
111
112
113
114
115
# File 'lib/pythonconfig.rb', line 108

def to_s
  output = ""
  @sections.each do |k,v|
    output << "[#{k}]\n"
    output << v.to_s
  end
  output
end