Class: Ini

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

Defined Under Namespace

Classes: NoFilenameError

Constant Summary collapse

DELIMITER =
"="
GLOBAL_SECTION =
"global"
COMMENT_SYMBOL =
";"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text = "") ⇒ Ini

Returns a new instance of Ini.



42
43
44
45
46
# File 'lib/ini.rb', line 42

def initialize(text = "")
  clear
  parse(text)
  @filename = nil
end

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



14
15
16
# File 'lib/ini.rb', line 14

def filename
  @filename
end

Class Method Details

.load(text) ⇒ Object



22
23
24
25
# File 'lib/ini.rb', line 22

def self.load(text)
  ini = new(text)
  ini.object
end

.load_file(file) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ini.rb', line 27

def self.load_file(file)
  case
  when file.kind_of?(String)
    text = File.read(file, mode: "r:BOM|UTF-8")
    ini = new(text)
    ini.filename = file
    return ini.object
  when file.respond_to?(:read)
    text = file.read
    return load(text)
  else
    raise NoFilenameError
  end
end

Instance Method Details

#cast(str) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ini.rb', line 74

def cast(str)
  value = nil
  case str
  when /^[+-]?\d+$/
    value = str.to_i
  when /^[+-]?\d*\.\d+$/
    value = str.to_f
  when /^true$/i
    value = true
  when /^false$/i
    value = false
  when /^(?:nil|null)$/i
    value = nil
  else
    if str.length > 0
      if str =~ /^(["'])(.+)\1$/
        value = $2
      else
        value = str
      end
    else
      value = nil
    end
  end
  value
end

#clearObject



52
53
54
# File 'lib/ini.rb', line 52

def clear
  @data = { GLOBAL_SECTION => {} }
end

#objectObject



48
49
50
# File 'lib/ini.rb', line 48

def object
  @data
end

#parse(text) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ini.rb', line 56

def parse(text)
  section = GLOBAL_SECTION
  text.each_line do |line|
    next if line.strip == ""
    next if line[0] == COMMENT_SYMBOL
    key, value = line.split(DELIMITER, 2).map(&:strip)
    if key && value
      @data[section][key] = cast(value)
      next
    end
    if /^\[(.+?)\]/ =~ line
      section = $1.strip
      @data[section] ||= {}
      next
    end
  end
end

#save(filename = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/ini.rb', line 101

def save(filename = nil)
  filename ||= @filename
  unless filename
    raise NoFilenameError
  end
  open(@filename, "w") do |fp|
    @data.each do |section, values|
      if section != GLOBAL_SECTION
        fp.puts("[#{section}]")
      end
      values.each do |key, value|
        value = "\"#{value}\"" if value.kind_of?(String)
        fp.puts("#{key} #{DELIMITER} #{value}")
      end
    end
  end
end