[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Dynamically access an class?

Steve L

4/18/2006 2:33:00 AM

How do I dynamically access a class in Ruby? (I think this is a Ruby
question and not a Rails question)

I want to be able to pass the name of a class into a method and have
that method be able to access the class of that name.


so a totally contrived use of this might be to pass the name a of class
into a method and have the method return an instance of that class


def test(class_name)
"class_name".new #this is what I don't know how to do...
end


test "Landlord" # Returns an instance of Landlord
test "Apartment" # Returns an instance of Apartment


Any ideas?


Janak


2 Answers

OliverMarchand

4/18/2006 7:11:00 AM

0

You can simply pass the class as an argument!

def factory_by_classref(myclass)
return myclass.new
end

class Landlord
def initialize
print "Did you pay your rent?\n"
end
end

class Apartment
def initialize
print "Don't pay that weird landlord!\n"
end
end

factory_by_classref Landlord
factory_by_classref Apartment

If you really need to pass a string then you need to use eval, which is
not such a nice solution.

def factory_by_string(str)
return eval str+".new"
end

factory_by_string "Landlord"
factory_by_string "Apartment"

ciao,
Oliver

ndh.00008B@gmail.com

4/18/2006 7:24:00 AM

0

Since classes are constants, you can get them through the module class
method const_get(someStringOrSymbol). But, I think that it would be
simpler just to pass the class constant itself, unless you are talking
about passing a string through a URL or something. There might be a
better way to do this, but this is what my looking through the API got
me.
The problem with this method is that it if the classes are not
available during runtime--they are not loaded into memory, it will
cause an error you would have to deal with because the constant won't
exist. But, I guess you probably expect that.



Here is some example code:

class LandLord
@name
attr_accessor :name
end

class Apartment
@floor
attr_accessor :floor
end


def test(klassStr)
Module.const_get(klassStr).new
end

apt=test("Apartment")
apt.floor = 1
bob = test("LandLord")
bob.name = "Bob, the Land Lord"
puts bob.name

#Or using the class as a constant

klass = LandLord
joe = klass.new
joe.name = "Joe, The Main Man"
puts joe.name