Object creation with a "variable classname"

C

cedric.ch

Hi,

I would to know if it is possible to do something like that:

def create_object(class_name)
my_object = **class_name**.new
end

I tried with class.new(&class_name)

Class_name = Class.new(&class_name)
my_object = Class_name.New

In fact I have a single table inheritence ( yes, I'm doing a Rails app
;) ). According to the action the user selects , I want to create the
apropriated object.

My English is very bad but I'll be very happy if you could help me.

Thanks :)
 
J

James Britt

cedric.ch said:
Hi,

I would to know if it is possible to do something like that:

def create_object(class_name)
my_object = **class_name**.new
end

I tried with class.new(&class_name)


x = Object.const_get( class_name ).new
 
C

cedric.ch

James Britt a écrit :
x = Object.const_get( class_name ).new



--
James Britt

"Inside every large system there's a small system trying to get out".
- Chet Hendrickson

Wow !
Thank you.
 
M

Mat Schaffer

x = Object.const_get( class_name ).new

Does that still work if there's a module mentioned in the string with
'::' included? I seem to remember a discussion or maybe an
eigenclass blog entry that mentioned the problem. But maybe I'm wrong.
-Mat
 
J

James Britt

Mat said:
Does that still work if there's a module mentioned in the string with
'::' included? I seem to remember a discussion or maybe an eigenclass
blog entry that mentioned the problem. But maybe I'm wrong.
-Mat

Well, try it and see:


module Foo
class Bar
def baz
warn 'BAZ!'
end
end
end

Foo::Bar.new.baz

Object.const_get( 'Foo::Bar' ).new.baz


http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/160468



--
James Britt

http://web2.0validator.com - We're the Dot in Web 2.0
http://www.rubyaz.org - Hacking in the Desert
http://www.jamesbritt.com - Playing with Better Toys
 

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,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top