Setting up global variables when hosting IronRuby in CLR

How to setup global variables in CLR that could be accessed by scripts
running in Iron Ruby engine hosted in CLR.

Some posts referred to the API Runtime.GetCurrentExecutionContext and
then setting up global variables there but in IronRuby version 1.1.3
this API is missing.

Ruby Script code (Test.rb):
class Test
def DoSomething()
puts “Value of global variable is #{$gVar}”
end
end

C# code:
// setup runtime etc
engine = runtime.GetEngine(“IronRuby”);

// setup global variables
// something like gVar = “Hello IronRuby”
scriptSource = engine.CreateScriptSourceFromFile(scriptFile)
scriptSource.Execute()

object myType = engine.Runtime.Globals.GetVariable(“Test”);
// Create a class instance
object myTypeObj = engine.Operations.CreateInstance(myType);
// Execute method
object result = engine.Operations.InvokeMember(myTypeObj,
“doSomething”);

Any help is greatly appreciated.

Thank you,
Ramesh

Ramesh,

You can still access RubyContext through
Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext.
The following extension method adds the old API back … if you need
it:

public static class IronRubyExtensions {
    public static RubyContext GetExecutionContext(this

ScriptEngine engine) {
return HostingHelpers.GetLanguageContext(engine) as
RubyContext;
}
}

Then setting a global variable from C# is:

engine.GetExecutionContext().DefineGlobalVariable("gVar", 42);

That being said, this API isn’t final and may change in future
versions of the DLR. If you rather use an API that is more final, and
you still really need to set a global variable, you could do it by
actually executing Ruby code:

dynamic scope = engine.CreateScope();
scope.gVar = 42
engine.Execute("$gVar = gVar", scope);

Now to the address my “if you need it” comments:
Ruby.GetExecutionContext(ScriptEngine) was removed from IronRuby 1.0
as we didn’t want to promote an hosting-level API that is
language-specific. Also, because it’s main usage is for setting global
variables (since there is no DLR-level API for Ruby globals), we felt
comfortable about introducing this breaking change as using Ruby
global variables is not a recommended practice (see
http://www.rubyist.net/~slagell/ruby/globalvars.html).

~Jimmy

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs