Best way to get a class object from its name?

W

Wes Gamble

All,

In my Rails app., I'm doing something like this:

eval("#{requested_controller_class}.respond_to?('session_data_not_needed_by?')")

where requested_controller_class is the name of an existing (controller)
class.

Is the above code the best of way of invoking respond_to? on the class
in question, or is there some better way to get the actual class object
based solely on it's name?

Thanks,
Wes
 
E

Ezra Zygmuntowicz

Hi~

All,

In my Rails app., I'm doing something like this:

eval("#{requested_controller_class}.respond_to?
('session_data_not_needed_by?')")

where requested_controller_class is the name of an existing
(controller)
class.

Is the above code the best of way of invoking respond_to? on the class
in question, or is there some better way to get the actual class
object
based solely on it's name?

Thanks,
Wes


Since you are in a Rails app the better way of doing that would be
like this:

requested_controller_class.constantize.respond_to? :session_data_not_nee
ded_by?


Cheers-
-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- (e-mail address removed)
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)
 
C

Chris Shea

All,

In my Rails app., I'm doing something like this:

eval("#{requested_controller_class}.respond_to?('session_data_not_needed_by?')")

where requested_controller_class is the name of an existing (controller)
class.

Is the above code the best of way of invoking respond_to? on the class
in question, or is there some better way to get the actual class object
based solely on it's name?

Thanks,
Wes

Getting class objects was one of the problems in Ruby Quiz #113. See:
http://www.ruby-forum.com/topic/97203 or
http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/90223b4082d864fa/

There are a couple of solutions given. Assuming your class name is in
the variable named 'quiz' this (from James II) does it:
quiz.split("::").inject(Object) { |par, const| par.const_get(const) }
 
B

Ben Bleything

eval("#{requested_controller_class}.respond_to?('session_data_not_needed_by?')")

where requested_controller_class is the name of an existing (controller)
class.

Is the above code the best of way of invoking respond_to? on the class
in question, or is there some better way to get the actual class object
based solely on it's name?
=> true

String#constantize is provided by Rails someplace. In non-Rails Ruby
code, you could do this:
=> true

Of course, if it's a single-level, you only need one of those.

Cheers,
Ben
 

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

Forum statistics

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

Latest Threads

Top