Dynamic class names

M

Martin Boese

Is it possible to create classes with a dynamic name? Example:

name = "Test"

class name # this fails
def write
puts "TEST"
end
end

puts Object::const_get(name).new.write # => "TEST"
 
P

Phillip Gawlowski

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Martin Boese wrote:
| Is it possible to create classes with a dynamic name? Example:
|
| name = "Test"
|
| class name # this fails
| def write
| puts "TEST"
| end
| end
|
| puts Object::const_get(name).new.write # => "TEST"
|
|
|
Yes. Here is an overview on metaprogramming, and two ways to create
classes dynamically:

http://ola-bini.blogspot.com/2006/09/ruby-metaprogramming-techniques.html

- -- Phillip Gawlowski
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEUEARECAAYFAkfzWNEACgkQbtAgaoJTgL9KhACfY0UzhdcpPeOYMYaOgjfUpT35
dAwAl3hEZTSDs6+M6U0givW4nk68iGU=
=44gD
-----END PGP SIGNATURE-----
 
M

Martin Boese

No... I mean the 'Name' of a class or module (that what you get with
object.class.name). The doc of Class::new (ri) describes how it works:
You can give a class a name by assigning the class object to a constant.

...but still that doesn't allow me to set the initial name when _defining_ the
class.

I am aware that this can be done using eval with the complete class definition
as a string - which is also not what I want.

The reason is to avoid name clashes of a larger program. So I am thinking of
using some central instance to assign names and address specific types of
classes.

Martin
 
R

Robert Dober

Is it possible to create classes with a dynamic name? Example:

name = "Test"

class name # this fails
def write
puts "TEST"
end
end

puts Object::const_get(name).new.write # => "TEST"
sure

c = Class::new {
def a; 41 end
}
d = Class::new(c) {
def a; super.succ end
}
d.new.a --> 42

HTH
Robert
 
M

Martin Boese

Thanks, that's what I was looking for.

That example of mine now works:

name = 'Test'
Object::const_set(name.intern, Class::new do
def write
puts "TEST"
end
end
)
Object::const_get(name).new.write # writes => "TEST"

martin
 

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,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top