Class: Minglr::ConfigParser

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

Constant Summary collapse

CONFIG_FILE =
".minglrconfig"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_contents) ⇒ ConfigParser

Returns a new instance of ConfigParser.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/minglr/config_parser.rb', line 20

def initialize(config_contents)
  @config = {}
  @current_section = nil
  config_contents.each_line do |line|
    line = line.strip!
    case line
    when "", /^#.*$/
      next
    when /\[(.*)\]/
      define_section($1.to_s)
    else
      define_var(line)
    end
  end
  @config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



6
7
8
# File 'lib/minglr/config_parser.rb', line 6

def config
  @config
end

Class Method Details

.parseObject



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/minglr/config_parser.rb', line 8

def self.parse
  config_files = [File.join(ENV["HOME"], CONFIG_FILE), File.join(ENV["PWD"], CONFIG_FILE)]
  config_files.uniq!
  config_files.each do |config_file_name|
    if File.exist?(config_file_name)
      return self.new(File.read(config_file_name)).config
    end
  end
  puts "Unable to find #{CONFIG_FILE} in #{config_files.join(", ")}"
  class_eval("send :exit, 1") # Why is it so hard to mock or stub exit?
end

Instance Method Details

#define_section(section_name) ⇒ Object



37
38
39
40
# File 'lib/minglr/config_parser.rb', line 37

def define_section(section_name)
  @config[section_name.to_sym] = {} unless @config.has_key?(section_name.to_sym)
  @current_section = section_name.to_sym
end

#define_var(line) ⇒ Object



42
43
44
45
46
47
# File 'lib/minglr/config_parser.rb', line 42

def define_var(line)
  key, value = line.split("=")
  key.strip!
  value.strip!
  @config[@current_section][key.to_sym] = value
end