WHITELEAF:Kindle応援サイト

KindleでWEB小説を読もう! Narou.rb 公開中

LimeChat で ini ファイルを読もう

prototype.js で書いてます。LimeChatprototype.js を使うには id:whiteleaf:20110326 あたりを参照。

//
// Simple Ini file controller
//
// [ ] で囲まれたものはセクションとして扱われ、それ以降のデータはセクションに所属する
// セクションが登場するまでのデータは global というセクションに割り当てられる
//
// var ini = new Ini("setting.ini");
// value1 = ini.data.global.key;
// value2 = ini.data.section.key;
//
var Ini = Class.create({
  delimiter: "=",
  global_section: "global",

  initialize: function(filename) {
    this.filename = filename;
  },

  clear: function() {
    this.data = { global: {} };
  },

  load: function() {
    this.clear();
    var file = openFile(this.filename);
    if (file) {
      var section = this.global_section;
      var line;
      while ((line = file.readLine()) != null) {
        if (line.trim() == 0) continue;
        if (/^\[(.+?)\]/.test(line)) {
          section = RegExp.$1.trim();
          if (!this.data[section]) {
            this.data[section] = {};
          }
          continue;
        }
        var res = line.split(this.delimiter);
        if (res.length != 2) continue;
        var key = res[0].trim(), value = res[1].trim();
        this.data[section][key] = value;
      }
      file.close();
      return true;
    }
    return false;
  },

  save: function() {
    var file = openFile(this.filename, false);
    if (file) {
      for (var section in this.data) {
        if (section != this.global_section) {
          file.writeLine("[" + section + "]");
        }
        for (var key in this.data[section]) {
          file.writeLine(key + this.delimiter + this.data[section][key]);
        }
      }
      file.truncate();
      file.close();
      return true;
    }
    return false;
  }
});