Class: Rubikon::Config::IniProvider

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

Overview

A configuration provider loading configuration data from INI files

Author:

  • Sebastian Staudt

Since:

  • 0.5.0

Class Method Summary collapse

Class Method Details

.load_config(file) ⇒ Hash

Loads a configuration Hash from a INI file

This method is taken from code written by gdsx in #ruby-lang (see snippets.dzone.com/posts/show/563).

Parameters:

  • file (String)

    The path of the file to load

Returns:

  • (Hash)

    The configuration data loaded from the file

Since:

  • 0.5.0



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
49
50
51
52
53
54
# File 'lib/rubikon/config/ini_provider.rb', line 23

def self.load_config(file)
  content = File.new(file).readlines.map do |line|
    line.gsub(/(?:#|;).*/, '').strip
  end.join("\n")

  config = {}
  content = content.split(/\[([^\]]+)\]/)[1..-1]
  content.inject([]) do |temp, field|
    temp << field
    if temp.length == 2
      value = temp[1].sub(/^\s+/,'').sub(/\s+$/,'')
      if config[temp[0]].nil?
        config[temp[0]] = value
      else
        config[temp[0]] << "\n#{value}"
      end
      temp.clear
    end
    temp
  end

  config.dup.each do |key, value|
    value_list = value.split /[\r\n]+/
    config[key] = value_list.inject({}) do |hash, val|
      k, v = val.split /\s*=\s*/
      hash[k] = v
      hash
    end
  end

  config
end

.save_config(config, file) ⇒ Object

Saves a configuration Hash into a INI file

Parameters:

  • config (Hash)

    The configuration to write

  • file (String)

    The path of the file to write

Since:

  • 0.6.0



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/rubikon/config/ini_provider.rb', line 61

def self.save_config(config, file)
  unless config.is_a? Hash
    raise ArgumentError.new('Configuration has to be a Hash')
  end

  file = File.new file, 'w'

  config.each do |key, value|
    if value.is_a? Hash
      file << "\n" if file.pos > 0
      file << "[#{key.to_s}]\n"

      value.each do |k, v|
        file << "  #{k.to_s} = #{v.to_s unless v.nil?}\n"
      end
    else
      file << "#{key.to_s} = #{value.to_s unless value.nil?}\n"
    end
  end

  file.close
end