Forum: IronRuby Setting up global variables when hosting IronRuby in CLR

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B1d03268d71afc3af108cc785d114803?d=identicon&s=25 Ramesh N. (ramesh_n)
on 2011-05-20 21:36
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
959b1c9d700abfc065f5f40bf5a966a2?d=identicon&s=25 James Schementi (jschementi)
on 2011-05-22 00:06
(Received via mailing list)
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 topic is locked and can not be replied to.