Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IronRuby as a scripting language in .NET

I want to use IronRuby as a scripting language (as Lua, for example) in my .NET project. For example, I want to be able to subscribe from a Ruby script to specific events, fired in the host application, and call Ruby methods from it.

I'm using this code for instantiating the IronRuby engine:

Dim engine = Ruby.CreateEngine()
Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile()
' Execute it
source.Execute()

Supposing index.rb contains:

subscribe("ButtonClick", handler)
def handler
   puts "Hello there"
end

How do I:

  1. Make C# method Subscribe (defined in host application) visible from index.rb?
  2. Invoke later handler method from the host application?
like image 429
rubyist111 Avatar asked May 27 '10 13:05

rubyist111


1 Answers

You can just use .NET events and subscribe to them within your IronRuby code. For example, if you have the next event in your C# code:

public class Demo
{
    public event EventHandler SomeEvent;
}

Then in IronRuby you can subscribe to it as follows:

d = Demo.new
d.some_event do |sender, args|
    puts "Hello there"
end

To make your .NET class available within your Ruby code, use a ScriptScope and add your class (this) as a variable and access it from within your Ruby code:

ScriptScope scope = runtime.CreateScope();
scope.SetVariable("my_class",this);
source.Execute(scope);

And then from Ruby:

self.my_class.some_event do |sender, args|
    puts "Hello there"
end

To have the Demo class available within the Ruby code so you can initialize it (Demo.new), you need to make the assembly "discoverable" by IronRuby. If the assembly is not in the GAC then add the assembly directory to IronRuby's search paths:

var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\My\Assembly\Path");
engine.SetSearchPaths(searchPaths);

Then in your IronRuby code you can require the assembly, for example: require "DemoAssembly.dll" and then just use it however you want.

like image 188
Shay Friedman Avatar answered Oct 19 '22 12:10

Shay Friedman