Best way to get a class object from its name?

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

Hi~

On Feb 22, 2007, at 1:21 PM, Wes G. wrote:

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 Z.
– Lead Rails Evangelist
[email protected]
– Engine Y., Serious Rails Hosting
– (866) 518-YARD (9273)

On Feb 22, 2:21 pm, Wes G. [email protected] wrote:

in question, or is there some better way to get the actual class object
based solely on it’s name?

Thanks,
Wes


Posted viahttp://www.ruby-forum.com/.

Getting class objects was one of the problems in Ruby Q. #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) }

On Fri, Feb 23, 2007, Wes G. wrote:

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?

str = “ActiveRecord::Base”
=> “ActiveRecord::Base”

str.constantize.respond_to? :new
=> true

String#constantize is provided by Rails someplace. In non-Rails R.
code, you could do this:

Module.const_get( ‘ActiveRecord’ ).const_get( ‘Base’ ).respond_to?
:find
=> true

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

Cheers,
Ben

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs