Forum: IronRuby Getting property list from both Ruby and .Net objects

382c3ae328b21e529ea0f5ddb1514abc?d=identicon&s=25 Alexander Ranger (strider_ajr)
on 2012-09-24 10:21
Hello.

I need some tools to get property names of both Ruby objects and .Net
objects. First I thought that there'll be no problem with it. I tried to
do it like:

def GetPropertyList(obj)
  return obj.instance_variables
end

But it turned out that when "obj" is a .Net object
obj.instance_variables returns nothing. Well, it returns an array but
array is empty.

For example:

require "Foo"
include FooModule

foo = Foo.new
foo.NetVal1 = "Hello"
foo.NetVal2 = 100

puts foo.class # => FooModule::Foo
puts foo.NetVal1 # => Hello
puts doo.NetVal2 # => 100

puts foo.instance_variables # =>             #it's blank here
puts foo.instance_variables.class # => Array


Well, then I thought that I can use reflection to get property list for
.Net objects:


def GetPropertyList(obj)
  array = Array.new
  obj.GetType().GetProperties.each do |prop|
    array.push prop.name
  end
  array
end


But it didn't work for a ruby object. I tried to somehow find out
weather object is from ruby or .Net and depending on it parse objects,
but I couldn't think of any working solution.

So my question is:
Give me a hint on how I can parse both ruby and .net objects using one
algorithm.

Thanks in advance,
Alex.
C94afbb820c49a847b3b1f5244178f82?d=identicon&s=25 Eduardo Blumenfeld (eblumenfeld)
on 2012-09-27 20:12
Hi Alex:

Try:

obj.methods
obj.public_methods
obj.private_methods

it will give you the list of all the methods available

(From the point of view of IronRuby, a .net object shows the methods

you would find

two methods for, one for set another for get of a variable,

for example, saying that you have a propety of the object called "name"

obj.name  (would return the actual setting for the variable (get) )

obj.name = "test".to_clr_string (would set the name in the .net object)

Note:
   .to_clr_string is important to convert the ruby string object to the
corresponding clr object (System::String)

Regards,

Eduardo
C94afbb820c49a847b3b1f5244178f82?d=identicon&s=25 Eduardo Blumenfeld (eblumenfeld)
on 2012-09-27 20:17
Alex:
A quick way of finding all the properties that you can set of a .net
object would be:

obj.methods.grep(/=/)

(filter by all the properties that you can set)
This topic is locked and can not be replied to.