Dynamic object construction

J

John Lam

------_=_NextPart_001_01C5448D.792B9DCA
Content-Type: text/plain;
charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

I'm trying to create a new object where the class of the object is
parameterized. My current solution is to use eval():

=20

def create(class)

@obj =3D eval("#{class}.new()")

end

=20

Is there a better way of doing this to avoid the hit of eval()?

=20

Thanks,

-John

http://www.iunknown.com

=20

=20


------_=_NextPart_001_01C5448D.792B9DCA--
 
B

Bill Atkins

------=_Part_346_25718566.1113881046339
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

If class is a a class name (a String):

@obj =3D Object.const_get(klass).new

Using "class" as a parameter name won't work - the standard is to use=20
"klass" instead.

Bill

=20
I'm trying to create a new object where the class of the object is
parameterized. My current solution is to use eval():
=20
def create(class)
=20
@obj =3D eval("#{class}.new()")
=20
end
=20
Is there a better way of doing this to avoid the hit of eval()?
=20
Thanks,
=20
-John
=20
http://www.iunknown.com
=20
=20


--=20
Bill Atkins

------=_Part_346_25718566.1113881046339--
 
G

George Moschovitis

@obj = Object.const_get(klass).new

does this work if klass == My::Namespace::Klass ?

-g.
 
T

Trans

George said:
does this work if klass == My::Namespace::Klass ?

Assuming you mean the string value

klass = "My::Namespace::Klass"

The answer is No. One has to do:

klass = "Klass"
@obj = My::Namespace.const_get(klass).new

The namespace issue is problematic. One alternative is in Ruby Facets:

require 'facet/object/constant'

klass == "My::Namespace::Klass"
@obj = constant(klass).new

T.
 
N

Nicholas Seckar

Assuming you mean the string value
klass = "My::Namespace::Klass"
The answer is No. One has to do...

Or the ever popular

klass.split('::').inject(Object) {|parent, name| parent.const_get(name)}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top