自作INIファイル操作モジュール
+
|
コード |
#
# FileName:: iniaccessor.rb
# Data:: 2007/10/24
# Autor:: mecha mogera
#
#
# = INIファイルアクセスモジュール
#
module INIAccessor
#
# === セクションの正規表現
#
SECTION_PATTERN = /^\s*\[[^\]]*\]\s*$/
#
# === keyとvalueを分ける正規表現
#
KEY_SPLIT_PATTERN = /\s*=\s*|\n/
#
# === コメント行の正規表現
#
COMMENT_PATTERN = /^\s*;/
#
# === INIの値読み込みメソッド
#
# _filename_ :: INIのファイル名
# _section_ :: セクション名
# _key_ :: キー名
# _defaultvalue_ :: デフォルト値(指定なしの時は空文字)
# return :: INIの値(文字列)
#
def self.read(filename, section, key, defaultvalue = "")
returnvalue = ""
begin
is_section = false
lines = IO.readlines(filename)
pos = get_position(lines, section, key)[1]
if (pos)
returnvalue = lines[pos].split(/\s*=\s*|\n/)[1]
end
rescue
returnvalue = ""
end
if (returnvalue.empty?)
return defaultvalue
end
return returnvalue
end
#
# == INIのセクションのkeyとvalueを全て取得
# _filename_ :: ファイル名
# _section_ :: セクション
# return :: key,valueの組み合わせのハッシュ
#
def self.reads(filename, section)
returnvalue = Hash.new
is_section = false
begin
IO.readlines(filename).each { |line|
if (line =~ COMMENT_PATTERN)
next
elsif (line.chomp =~ /^\s*\[#{section}\]\s*$/)
is_section = true
next
elsif (line.chomp =~ SECTION_PATTERN)
is_section = false
next
elsif (is_section)
key_and_value = line.chomp.split(KEY_SPLIT_PATTERN)
if key_and_value[0] && !key_and_value[0].empty?
value = key_and_value[1]
unless value
value = ""
end
returnvalue[key_and_value[0]] = value
end
end
}
rescue
end
return returnvalue
end
#
# === INIの値書き込みメソッド
#
# _filename_ :: INIのファイル名
# _section_ :: セクション名
# _key_ :: キー名
# _value_ :: 書き込む値(数字、文字列可)
#
def self.write(filename, section, key, value)
if (File.exist?(filename))
lines = IO.readlines(filename)
else
lines = Array.new
end
section_pos, key_pos = get_position(lines, section, key)
if (key_pos)
lines[key_pos] = "#{key}=#{value}\n"
elsif (section_pos)
lines.insert(section_pos + 1, "#{key}=#{value}\n")
else
lines << "[#{section}]\n"
lines << "#{key}=#{value}\n"
end
f = File.new(filename, "w")
f.print lines
f.close
end
#
# === INIの値が書き込んである場所を示すメソッド(モジュールprivateなメソッド)
# 現在のruby(1.85)ではモジュールprivateなメソッドは実現できないらしい
#
# _lines_ :: INIファイルの全ての行
# _section_ :: セクション名
# _key_ :: キー名
# return :: [セクション行の位置(default:nil), キー行の位置(default:nil)]
#
def self.get_position(lines, section, key)
is_section = false
section_pos = nil
for i in 0...lines.length
line = lines[i]
if (line.chomp =~ COMMENT_PATTERN)
next
elsif (line.chomp =~ /^\s*\[#{section}\]\s*$/)
section_pos = i
is_section = true
next
elsif (line.chomp =~ SECTION_PATTERN)
is_section = false
next
elsif (is_section)
key_and_value = line.split(KEY_SPLIT_PATTERN)
if (key_and_value[0] == key)
return [section_pos, i]
end
end
end
return [section_pos, nil]
end
end
|
その他モジュール
ネットで検索して見つけたINIファイルの操作モジュールです。
モジュールは下記のサイトにあります。
Win32APIを利用してINIファイルの操作を行うようです。
最終更新:2008年06月16日 21:34