public ICondition Create() { this.engine = Ruby.CreateEngine(); var rubyRuleTemplate = String.Empty; using (var stream = new StreamReader(this.dslFileName)) { rubyRuleTemplate = stream.ReadToEnd(); } rubyRuleTemplate = rubyRuleTemplate.Replace("$ruleAssembly$", this.contextType.Namespace.Replace(".", "::")); rubyRuleTemplate = rubyRuleTemplate.Replace("$contextType$", this.contextType.Name); rubyRuleTemplate = rubyRuleTemplate.Replace("$condition$", this.condition); this.source = engine.CreateScriptSourceFromString(rubyRuleTemplate); var scope = engine.CreateScope(); assemblies.ForEach(a => engine.Runtime.LoadAssembly(a)); engine.Execute(source.GetCode(), scope); var @class = engine.Runtime.Globals.GetVariable("RuleRuleFactory"); var installer = engine.Operations.CreateInstance(@class); var rule = installer.Create(); return((ICondition)rule); }
static void Main(string[] args) { var engine = Ruby.CreateEngine(); var scope = engine.ExecuteFile("libtest.rb"); dynamic globals = engine.Runtime.Globals; var klass = globals.Klass; var klass_s = klass.GetOrCreateSingletonClass(); var modul = globals.Modul; var modul_s = modul.GetOrCreateSingletonClass(); Console.WriteLine( scope.GetVariable <IronRuby.Builtins.RubyMethod>( "method_in_the_global_object").Name); Action <string, IronRuby.Builtins.RubyModule, IronRuby.Runtime.Calls.RubyMemberInfo> classprinter = (n, k, i) => { Console.WriteLine(n, k, i); }; klass.ForEachMember(false, IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); klass_s.ForEachMember(false, IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); modul.ForEachMember(false, IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); modul_s.ForEachMember(false, IronRuby.Runtime.RubyMethodAttributes.Default, classprinter); Console.ReadLine(); }
public ICondition Create() { _engine = Ruby.CreateEngine(); string rubyRuleTemplate; using (var stream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream(_dslFileName)) { using (var reader = new StreamReader(stream)) { rubyRuleTemplate = reader.ReadToEnd(); } } rubyRuleTemplate = rubyRuleTemplate.Replace("$ruleAssembly$", _contextType.Namespace.Replace(".", "::")); rubyRuleTemplate = rubyRuleTemplate.Replace("$contextType$", _contextType.Name); rubyRuleTemplate = rubyRuleTemplate.Replace("$condition$", _condition); _source = _engine.CreateScriptSourceFromString(rubyRuleTemplate); var scope = _engine.CreateScope(); _assemblies.ForEach(a => _engine.Runtime.LoadAssembly(a)); _engine.Execute(_source.GetCode(), scope); var @class = _engine.Runtime.Globals.GetVariable("RubyRuleFactory"); var installer = _engine.Operations.CreateInstance(@class); var rule = installer.Create(); return((ICondition)rule); }
public static void Main() { // Ruby エンジンを生成 ScriptEngine engine = Ruby.CreateEngine(); // スコープとソースを生成 ScriptScope scope = engine.CreateScope(); ScriptSource source = engine.CreateScriptSourceFromFile("script.rb"); // グローバル変数を設定 scope.SetVariable("number1", 3.14159265); scope.SetVariable("number2", 2.71828182); scope.SetVariable("string", "This is a ruby script."); scope.SetVariable("boolean", true); scope.SetVariable("some_object", new SomeObject()); // 実行した後の戻り値を出力 Console.WriteLine("[ Output from Ruby ]\n"); source.Execute(scope); // グローバル変数の取得 Console.Write("\n\n\n"); Console.WriteLine("[ Output from C# ]\n"); Console.WriteLine(scope.GetVariable("number_ret")); Console.WriteLine(scope.GetVariable("string_ret")); Console.WriteLine(scope.GetVariable("boolean_ret")); }
public bool Initialize(string taskName, IDictionary <string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { var projectFileDirectory = Path.GetDirectoryName(taskFactoryLoggingHost.ProjectFileOfTaskNode); var thisAssemblyDirectory = Path.GetDirectoryName(this.GetType().Assembly.Location); _assemblyResolver.BeginResolving(thisAssemblyDirectory, projectFileDirectory); try { var engine = Ruby.CreateEngine(); _taskScriptScope = engine.CreateScope(); _taskScriptScope.ExecuteEmbeddedScript(RubyTaskScript); var rubyTaskBody = TaskBodyParser.Parse(taskBody); var scriptFile = projectFileDirectory.CombinePath(rubyTaskBody.Script).ToFullPath(); var scriptContents = _fileSystem.GetFileContent(scriptFile); _taskScriptScope.Execute(scriptContents); _taskClass = engine.Runtime.Globals.GetVariable(taskName); } catch (Exception) { _assemblyResolver.Dispose(); throw; } return(true); }
private ScriptEngine CreateAndInitEngine() { var engine = Ruby.CreateEngine(); engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); // set library/assembly search paths // (used by require and load_assembly) var libPathProvider = new LibraryPathFile(m_pathResolver, @"path.txt"); engine.SetSearchPaths(libPathProvider.Paths); // Expose global objects var ctx = HostingHelpers.GetLanguageContext(engine) as RubyContext; ctx.DefineReadOnlyGlobalVariable( "onError", new Action <MutableString, RubyArray>(TriggerErrorEventFromRuby) // #onError(message, backtrace) ); // HACK: needed to set $0 == <main script filename> ctx.DefineGlobalVariable("0", Path.GetFileName(MainScript)); ctx.DefineReadOnlyGlobalVariable("pr", m_pathResolver); // Create initial script source m_scriptSrc = engine.CreateScriptSourceFromFile( MainScript, Encoding.UTF8, SourceCodeKind.File ); // Set new IO streams RedirectIOStreams(engine); return(engine); }
public Result OnStartup(UIControlledApplication application) { //Create panel var ribbonPanel = application.CreateRibbonPanel("Ruby scripting"); var pushButton = ribbonPanel.AddItem( new PushButtonData( "RevitRubyShell", "Open Shell", typeof(RevitRubyShellApplication).Assembly.Location, "RevitRubyShell.ShellCommand")) as PushButton; pushButton.LargeImage = GetImage("console-5.png"); //Start ruby interpreter _rubyEngine = Ruby.CreateEngine(); _scope = _rubyEngine.CreateScope(); // Warm up the Ruby engine by running some code on another thread: new SThread.Thread( () => { var defaultScripts = GetSettings().Root.Descendants("OnLoad").ToArray(); var script = defaultScripts.Any() ? defaultScripts.First().Value.Replace("\n", "\r\n") : ""; _rubyEngine.Execute(script, _scope); }).Start(); RevitRubyShellApplication.RevitRubyShell = this; application.Idling += (sender, args) => { var uiapp = sender as UIApplication; lock (this.Queue) { if (this.Queue.Count <= 0) { return; } var task = this.Queue.Dequeue(); // execute the task! try { task(uiapp); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } }; var win = new ShellWindow(); application.RegisterDockablePane(new DockablePaneId(DockGuid), "RevitRubyShell", win); return(Result.Succeeded); }
private void LoadPlugins() { var engine = Ruby.CreateEngine(); var scope = engine.CreateScope(); var paths = engine.GetSearchPaths().ToList(); paths.Add(Settings.PATH + "plugins"); engine.Execute("plugin.rb"); }
static void Main() { var rubyEngine = Ruby.CreateEngine(); rubyEngine.ExecuteFile("method_missing_demo.rb"); dynamic globals = rubyEngine.Runtime.Globals; dynamic methodMissingDemo = globals.MethodMissingDemo.@new(); Console.WriteLine(methodMissingDemo.HelloDynamicWorld()); methodMissingDemo.print_all(args); }
protected override object RunScriptCore() { ScriptEngine engine = Ruby.CreateEngine(); foreach (var item in Variables) { engine.Runtime.Globals.SetVariable(item.Key, item.Value); } return(engine.Execute(Script)); }
public MDbgScriptForm(SptWrapper ext) { _host = Ruby.CreateEngine(); _scope = _host.CreateScope(); _scope.SetVariable("ext", ext); _scope.SetVariable("dbg", new Environment(this)); _ext = ext; InitializeComponent(); }
public void TC001_TestRuby() { //Arrange var engine = Ruby.CreateEngine(); //Act dynamic result = engine.Execute(" 'test' "); //Assert Assert.AreEqual(result.ToString(), "test"); }
public override void Reset(ScriptScope scope) { _engine = Ruby.CreateEngine((setup) => { setup.Options["InterpretedMode"] = true; setup.Options["SearchPaths"] = new[] { MerlinPath + @"\libs", BasePath + @"\ruby\site_ruby\1.8", BasePath + @"\ruby\site_ruby", BasePath + @"\ruby\1.8" }; }); _scope = scope == null?_engine.Runtime.CreateScope() : scope; _topLevelBinding = (IronRuby.Builtins.Binding)_engine.Execute("binding", _scope); }
public SourceUnitTree CreateAst(string fileName, ITextBuffer fileContent) { if (scriptEngine == null) { scriptEngine = Ruby.CreateEngine(); } RubyContext rubyContext = HostingHelpers.GetLanguageContext(scriptEngine) as RubyContext; sourceUnit = rubyContext.CreateFileUnit(fileName, fileContent.Text); RubyCompilerSink sink = new RubyCompilerSink(); RubyCompilerOptions compilerOptions = new RubyCompilerOptions((RubyOptions)rubyContext.Options); Parser parser = new Parser(); return parser.Parse(sourceUnit, compilerOptions, sink); }
public void ConstantCaching_CrossRuntime1() { var engine2 = Ruby.CreateEngine(); var c = Engine.Execute(@" module C X = 1 end C "); ((RubyContext)HostingHelpers.GetLanguageContext(engine2)).DefineGlobalVariable("C", c); var m = engine2.Execute(@" module M module N O = $C end end M "); Context.DefineGlobalVariable("M", m); TestOutput(@" module D E = $M end module Z module O X = 2 end end i = 0 while i < 6 puts D::E::N::O::X rescue p $! # tested cache $M.send(:remove_const, :N) if i == 1 $M.send(:const_set, :N, Z) if i == 3 i += 1 end ", @" 1 1 #<NameError: uninitialized constant M::N> #<NameError: uninitialized constant M::N> 2 2 "); }
public RubyRuleEngine() { Trace.WriteLine("Ruby Rule Engine loaded..."); _engine = Ruby.CreateEngine(); CustomRuleCode = @"# Ruby Code if text.nil? or text.empty? return false else return true end"; }
public static IEnumerable <IHostingContext> CreateHostingContexts(HostingContextConfigurer configurer) { var python = new DlrHostingContext(Python.CreateEngine(), "Samples.script.py"); configurer.Configure(python); var ruby = new DlrHostingContext(Ruby.CreateEngine(), "Samples.script.rb"); configurer.Configure(ruby); var js = new JSHostingContext("Samples.script.js"); configurer.Configure(js); return(new IHostingContext[] { python, ruby, js }); }
/// <summary> /// Creates an engine of the relevant DLR language type. /// </summary> /// <param name="language">the strongly-typed language name</param> private ScriptEngine CreateEngine(Languages language) { switch (language) { case Languages.IronPython: return(Python.CreateEngine()); case Languages.IronRuby: return(Ruby.CreateEngine()); default: return(null); } }
public void TC002_TestRubyVars() { //Arrange var engine = Ruby.CreateEngine(); var scope = engine.CreateScope(); scope.SetVariable("myVar", "test"); //Act dynamic result = engine.Execute(" myVar ", scope); //Assert Assert.AreEqual(result.ToString(), "test"); }
public void RubyHosting4() { // TODO: LanguageSetup should have an indexer: //var ruby = Ruby.CreateEngine((setup) => { // setup["InterpretedMode"] = true; // setup["SearchPaths"] = "blah"; //}); var ruby = Ruby.CreateEngine((setup) => { setup.InterpretedMode = true; }); Debug.Assert(ruby.Setup.InterpretedMode == true); }
public static dynamic GetIronRubyRunitimeGlobals(IDictionary <string, object> variables, string fileToExecute) { var engine = Ruby.CreateEngine(); var scope = engine.CreateScope(); variables?.ForEach(v => scope.SetVariable(v.Key, v.Value)); if (!string.IsNullOrEmpty(fileToExecute)) { engine.ExecuteFile(fileToExecute, scope); } return(engine.Runtime.Globals); }
/// <summary> /// 读取连接配置文件 /// </summary> public static void ConfigRead() { var rubyEngine = Ruby.CreateEngine(); rubyEngine.ExecuteFile(Constant.Config); dynamic ruby = rubyEngine.Runtime.Globals; dynamic config = ruby.Config.@new(); #region 获取SSH连接信息 Constant.sshServer = config.getServer().ToString(); Constant.sshPort = int.Parse(config.getPort().ToString()); Constant.sshUID = config.getUID().ToString(); Constant.sshPWD = config.getPWD().ToString(); #endregion }
/// <summary> /// Loads a map data file based on ID and parses it to C# object. /// </summary> public static Map Parse(int id) { Dictionary <string, dynamic> Data = new Dictionary <string, dynamic>(); List <List <dynamic> > Layers = new List <List <dynamic> >(); ScriptEngine engine = Ruby.CreateEngine(); dynamic ret = engine.Execute($@" f = File.open(""Maps/{Digits(id)}.mkd"", ""rb"") Data = Marshal.load(f) f.close return [Data[0],Data[1..-1]]"); // Parses the Layer data to C# objects (in Lists instead of Arrays) dynamic[] _layers = ret[1].ToArray(); for (int i = 0; i < _layers.Length; i++) { List <dynamic> Layer = new List <dynamic>(); dynamic[] _layer = ((IronRuby.Builtins.RubyArray)_layers[i]).ToArray(); for (int j = 0; j < _layer.Length; j++) { if (_layer[j] is IronRuby.Builtins.RubyArray) { dynamic[] _tile = ((IronRuby.Builtins.RubyArray)_layer[j]).ToArray(); List <dynamic> Tile = new List <dynamic>(); for (int k = 0; k < _tile.Length; k++) { int TileData = Convert.ToInt32(_tile[k].ToString()); Tile.Add(TileData); } Layer.Add(Tile); } else { Layer.Add(Convert.ToInt32(_layer[j].ToString())); } } Layers.Add(Layer); } int Width = Convert.ToInt32(ret[0][0].ToString()); int Height = Convert.ToInt32(ret[0][1].ToString()); string Tileset = ret[0][2].ToString(); string Name = ret[0][3].ToString(); return(new Map(id, Layers, Width, Height, Tileset, Name)); }
static IronRubyParser() { var engine = Ruby.CreateEngine(); // ir.exe.config を参照のこと engine.SetSearchPaths(new[] { @"ParserScripts\IronRubyParser", }); var scope = engine.CreateScope(); var source = engine.CreateScriptSourceFromFile(@"ParserScripts\IronRubyParser\parser.rb"); source.Execute(scope); ParseCodeFunc = scope.GetVariable <Func <string, XElement> >("parse_code"); ParseXmlFunc = scope.GetVariable <Func <XElement, string> >("parse_xml"); }
public static void Run() { dynamic pp = Ruby.CreateEngine().CreateScriptSourceFromFile("Dynamic/preprompt.rb").Execute(); foreach (var session in pp.sessions) { Console.WriteLine(session.title); Console.WriteLine("Speakers:"); foreach (var speaker in session.speakers) { Console.WriteLine("\t" + speaker); } } Console.WriteLine(); Extensions.ForEach(pp.sessions, new Action <dynamic>(session => Console.WriteLine(session.to_s()))); }
public bool Load() { Unload(); if (homegenie == null) { return(false); } scriptEngine = Ruby.CreateEngine(); hgScriptingHost = new ScriptingHost(); hgScriptingHost.SetHost(homegenie, programBlock.Address); dynamic scope = scriptScope = scriptEngine.CreateScope(); scope.hg = hgScriptingHost; return(true); }
public List <ProgramError> Compile() { List <ProgramError> errors = new List <ProgramError>(); var engine = Ruby.CreateEngine(); var source = engine.CreateScriptSourceFromString(programBlock.ScriptCondition); var errorListener = new ScriptEngineErrors("TC"); source.Compile(errorListener); errors.AddRange(errorListener.Errors); errorListener = new ScriptEngineErrors("CR"); source = engine.CreateScriptSourceFromString(programBlock.ScriptSource); source.Compile(errorListener); errors.AddRange(errorListener.Errors); engine.Runtime.Shutdown(); engine = null; return(errors); }
internal static string SetRbScriptedSend(string FunctionCode) { ScriptEngine Engine = Ruby.CreateEngine(); StringBuilder FullCode = new StringBuilder(); FullCode.AppendLine("include IronWASP"); FullCode.AppendLine("class SS < ScriptedSender"); FullCode.AppendLine(" def scripted_send(req)"); string[] CodeLines = FunctionCode.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string Line in CodeLines) { FullCode.Append(" "); FullCode.AppendLine(Line); } FullCode.AppendLine(" return res"); FullCode.AppendLine(" end"); FullCode.AppendLine("end"); FullCode.AppendLine(""); FullCode.AppendLine("s = SS.new"); FullCode.AppendLine("ManualTesting.set_scripted_sender(s)"); return(SetScriptedSend(Engine, FullCode.ToString())); }
public void TC003_TestERB() { //Arrange string template = "<%= x %>"; var engine = Ruby.CreateEngine(); var scope = engine.CreateScope(); scope.SetVariable("templateText", template); //Act dynamic result = engine.Execute(@" require 'Ruby\erb.rb' x = 'test' template = ERB.new(templateText.to_s) res = template.result(binding) ", scope); //Assert Assert.AreEqual(result.ToString().Trim(), "test"); }
private void CreateScriptEngine() { vars = new Dictionary <string, object>(); scriptEngine = Ruby.CreateEngine(); #if DEBUG string baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", ".."); #else string baseDir = AppDomain.CurrentDomain.BaseDirectory; #endif string rubylibDir = Path.Combine(baseDir, "rubylib"); string scriptsDir = Path.Combine(baseDir, "scripts"); List <string> searchPaths = new List <string>(); // searchPaths.Add(baseDir); searchPaths.Add(Path.Combine(rubylibDir, "IronRuby")); searchPaths.Add(Path.Combine(rubylibDir, "ruby", "site_ruby", "1.9.1")); searchPaths.Add(Path.Combine(rubylibDir, "ruby", "site_ruby")); searchPaths.Add(Path.Combine(rubylibDir, "ruby", "1.9.1")); searchPaths.Add(Path.Combine(rubylibDir, "vendor")); scriptEngine.SetSearchPaths(searchPaths); scriptEngine.Runtime.Globals.SetVariable("Native", this); //fileSystemWatcher = new FileSystemWatcher(baseDir, rubylibDir); //fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; //fileSystemWatcher.IncludeSubdirectories = true; //fileSystemWatcher.Filter = "*.rb"; //fileSystemWatcher.Changed += fileSystemWatcher_Changed; //fileSystemWatcher.Created += fileSystemWatcher_Created; //fileSystemWatcher.Deleted += fileSystemWatcher_Deleted; //fileSystemWatcher.Renamed += fileSystemWatcher_Renamed; //fileSystemWatcher.EnableRaisingEvents = true; }