// komodo tool: rails console
// ==========================
// async: 0
// icon: chrome://famfamfamsilk/skin/icons/application_osx_terminal.png
// language: JavaScript
// rank: 100
// trigger: trigger_postopen
// trigger_enabled: 0
// type: macro
// version: 1.0.13
// ==========================
(function() {
    try {
        var railsVersion = ko.extensions.rails.getRailsVersionInRange(1, 5);
        if (railsVersion[0] >= 2 ||
            Components.classes['@activestate.com/koInfoService;1'].getService(Components.interfaces.koIInfoService).platform !=
                'darwin') {
            var cmd_by_version = {
                2: 'script/console',
                3: 'script/rails console',
                4: 'bin/rails console',
                5: 'bin/rails console'
            };
            cmd_by_version[1] = cmd_by_version[2];
            let cmd = cmd_by_version[railsVersion];
            ko.extensions.rails.launchRubyAppInConsole(window, cmd);
            return;
        }
        var rawRubyPath = ko.extensions.rails.get_path_by_ko_pref('ruby');
        var osPathSvc =
            Components.classes["@activestate.com/koOsPath;1"].getService(Components.interfaces.koIOsPath);
        var rubyDir = osPathSvc.dirname(rawRubyPath);
        var irbPath = osPathSvc.join(rubyDir, 'irb');
        if (!osPathSvc.exists(irbPath)) {
            irbPath = null;
            var candidates = {"irb.sh" : 1, "irb.bat" : 1, "irb.cmd" : 1 };
            var resultObj = {};
            var filenames = (Components.classes["@activestate.com/koOs;1"].
                     getService(Components.interfaces.koIOs).listdir(rubyDir, resultObj));
            for (var idx in filenames)  {
                var fname = filenames[idx];
                if (fname in candidates)  {
                    irbPath = osPathSvc.join(rubyDir, fname);
                    break;
                }
            }
            if (!irbPath) {
                alert(ko.extensions.rails.bundle.formatStringFromName('Sorry cant find a version of irb in the directory',
                                                  [rubyDir], 1));
                prefs_doGlobalPrefs('rubyItem');
                return;
            }
        }
        if (/[^\w.:\-\"\'\\\/]/.test(irbPath)) {
            irbPath = '"' + irbPath + '"';
        }
        var cmd = 'script/console --irb=' + irbPath;
        ko.extensions.rails.launchRubyAppInConsole(window, cmd);
   } catch(ex) {
       alert(ex + "\n");
   }
})();