views:

169

answers:

1

Hello anyone!

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

I'm using this code for instantiate 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. Set C# method Subscribe (defined in host application) visible from index.rb?
  2. Invoke later handler method from host application?

Thanks a lot!

+2  A: 

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.

Shay Friedman
Thank you a lot.But 1 question remains. How to make available Demo class (not instance of it) within ruby code in such way that we would be able to instantiate it? For example: d = Demo.new
rubyist111
Added the answer to the body of the original answer above.
Shay Friedman