Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding support for a default global section

If a property does not appear under any section, then it will be added to a
default "global" section. The name of this default section is configurable.
  • Loading branch information...
commit c855bc07b3e0b485dcee7687895c71d46ad3fdc2 1 parent 2d6ffe5
Tim Pease authored
View
3  lib/inifile.rb
@@ -52,6 +52,7 @@ def initialize( filename, opts = {} )
@param = opts.fetch(:parameter, '=')
@encoding = opts.fetch(:encoding, nil)
@escape = opts.fetch(:escape, true)
+ @default = opts.fetch(:default, 'global')
@ini = Hash.new {|h,k| h[k] = Hash.new}
@rgxp_comment = %r/\A\s*\z|\A\s*[#{@comment}]/
@@ -411,7 +412,7 @@ def parse_property( line )
def finish_property
return unless @_current_param
- raise Error, "parameter encountered before first section" if @_current_section.nil?
+ @_current_section = @ini[@default] if @_current_section.nil?
@_current_section[@_current_param] = unescape @_current_value
@_current_param = nil
View
6 test/data/bad_1.ini
@@ -1,6 +1,6 @@
-; having a paramater / value pair outside a section is an error
-one = 1
-
[section_one]
one = 1
two = 2
+
+; the following is not a valid line
+invalid line
View
6 test/data/bad_2.ini
@@ -1,6 +0,0 @@
-[section_one]
-one = 1
-two = 2
-
-; the following is not a valid line
-invalid line
View
3  test/data/global.ini
@@ -0,0 +1,3 @@
+; without any section, a default 'global' section will be created
+one = 1
+two = 2
View
17 test/test_inifile.rb
@@ -57,7 +57,6 @@ def test_class_load
# make sure we error out on files with bad lines
assert_raise(IniFile::Error) {IniFile.load 'test/data/bad_1.ini'}
- assert_raise(IniFile::Error) {IniFile.load 'test/data/bad_2.ini'}
end
def test_clone
@@ -254,7 +253,6 @@ def test_initialize
# make sure we error out on files with bad lines
assert_raise(IniFile::Error) {IniFile.new 'test/data/bad_1.ini'}
- assert_raise(IniFile::Error) {IniFile.new 'test/data/bad_2.ini'}
end
def test_sections
@@ -439,5 +437,20 @@ def test_value_escaping_disabled
assert_equal %q{This string \\\\t contains \\\\n no \\\\r special \\\\0 characters!}, escaped['backslash']
end
+ def test_global_section
+ ini_file = IniFile.load('test/data/global.ini')
+
+ assert_equal %w[global], ini_file.sections
+ assert_equal '1', ini_file['global']['one']
+ assert_equal '2', ini_file['global']['two']
+ end
+
+ def test_default_global_section
+ ini_file = IniFile.load('test/data/global.ini', :default => 'nonce')
+
+ assert_equal %w[nonce], ini_file.sections
+ assert_equal '1', ini_file['nonce']['one']
+ assert_equal '2', ini_file['nonce']['two']
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.