tags:

views:

59

answers:

2

After executing this code:

    var runtime = IronRuby.Ruby.CreateRuntime();
    var engine = IronRuby.Ruby.CreateEngine();
    var scrope = engine.CreateScope();
    engine.ExecuteFile("libtest.rb");

How can I get all the methods of a ruby class in c# code?

+1  A: 

Or you can do it from C# http://github.com/casualjim/ironrubymvc/blob/master/IronRubyMvc/Core/RubyEngine.cs#L178

If you define methods without having them in a class they should get added to the Object class

Casual Jim
+1  A: 

I haven't figured everything out yet, but here's a start:

using System;
using IronRuby;
using Microsoft.Scripting.Hosting;

class IronRubyReflection
{
    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();
    }
}

Forgive my style, I don't actually know C#.

This is my libtest.rb:

def method_in_the_global_object; end

class Klass
  def instance_method_in_class; end
  def self.class_method; end
end

class Modul
  def instance_method_in_module; end
  def self.module_method; end
end

local = Object.new
def local.singleton_meth; end

@instance = Object.new
def @instance.singleton_meth; end

$global = Object.new
def $global.singleton_meth; end

And this is the output:

method_in_the_global_object
instance_method_in_class
class_method
Equals
ReferenceEquals
allocate
clr_constructor
clr_ctor
clr_new
new
superclass
instance_method_in_module
module_method
Equals
ReferenceEquals
allocate
clr_constructor
clr_ctor
clr_new
new
superclass

Jörg W Mittag