How to get a new instance of a class given a String

Hey,

I know I have seen his on the list before but I can't seem to find it.

I want to do something like

class_name = "UserPreference"
up = Class.class_for_name(class_name).new

Anyone?

Also, where would be a good place for me to find a reference for all the
very useful methods for Meta Programming?

Thanks,

Dave

up = Object.const_get(class_name).new

-- Daniel

···

On May 2, 2006, at 5:03 PM, David Clements wrote:

class_name = "UserPreference"
up = Class.class_for_name(class_name).new

David Clements wrote:

Hey,

I know I have seen his on the list before but I can't seem to find it.

I want to do something like

class_name = "UserPreference"
up = Class.class_for_name(class_name).new

Anyone?

Also, where would be a good place for me to find a reference for all the
very useful methods for Meta Programming?

ins and outs of const_get:

http://groups.google.com/group/comp.lang.ruby/browse_frm/thread/49c924bbea4551f4/f502387ee9b458fe?hl=en#f502387ee9b458fe

metap'g / DSL's:

http://www.mail-archive.com/pdxruby@lists.pdxruby.org/msg00416.html

http://redhanded.hobix.com/bits/evalLessMetaprogramming.html

http://jamis.jamisbuck.org/articles/2006/04/20/writing-domain-specific-languages
http://dppruby.com/dppsrubyplayground/files/Preso.ppt
yah, itps powerpoint, but worth it to go find a win32 machine
http://www.devsource.com/print_article2/0,1217,a=171834,00.asp

Generalizing Daniel's solution:

543> cat tClassByName.rb #!/bin/ruby -w

def class_by_name name
    name.split("::").inject(Object){ |c,n|
        c.const_get(n)
    }
end

p class_by_name( 'Hash' )
p class_by_name( 'File::Stat' )
__END__

544> ruby tClassByName.rb
Hash
File::Stat

regards
Sergey

···

----- Original Message ----- From: "Daniel Harple" <dharple@generalconsumption.org>
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Tuesday, May 02, 2006 11:06 AM
Subject: Re: How to get a new instance of a class given a String

On May 2, 2006, at 5:03 PM, David Clements wrote:

class_name = "UserPreference"
up = Class.class_for_name(class_name).new

up = Object.const_get(class_name).new

-- Daniel

Generalizing Daniel's solution:

543> cat tClassByName.rb
#!/bin/ruby -w

def class_by_name name
    name.split("::").inject(Object){ |c,n|
        c.const_get(n)
    }
end

p class_by_name( 'Hash' )
p class_by_name( 'File::Stat' )
__END__

544> ruby tClassByName.rb
Hash
File::Stat

regards
Sergey

Thanks so much that has me going again.

Dave

···

On 5/2/06, Sergey Volkov <gm.vlkv@gmail.com> wrote:

----- Original Message -----

From: "Daniel Harple" <dharple@generalconsumption.org>
To: "ruby-talk ML" <ruby-talk@ruby-lang.org>
Sent: Tuesday, May 02, 2006 11:06 AM
Subject: Re: How to get a new instance of a class given a String

> On May 2, 2006, at 5:03 PM, David Clements wrote:
>
>> class_name = "UserPreference"
>> up = Class.class_for_name(class_name).new
>
> up = Object.const_get(class_name).new
>
> -- Daniel