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.



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

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

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



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

def filename
  @filename
end

Class Method Details

.load(text) ⇒ Object



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

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

.load_file(file) ⇒ Object



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

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



73
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
# File 'lib/ini.rb', line 73

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



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

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

#objectObject



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

def object
  @data
end

#parse(text) ⇒ Object



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

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



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

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