Other way instead of this evil eval?

I am trying to do this, where associated_record_type is always of the
name
of a model, passed to the method:

record =
eval("#{associated_record_type}").find_by_id(associated_record_id)

Is there a way to do this dynamically without using an eval?

On 3 May 2011 20:26, David K. [email protected] wrote:

record = eval("#{associated_record_type}").find_by_id(associated_record_id)

Is there a way to do this dynamically without using an eval?

record =
associated_record_type.classify.constantize.find_by_id(associated_record_id)

On 3 May 2011 20:30, Michael P. [email protected] wrote:

On 3 May 2011 20:26, David K. [email protected] wrote:

record = eval("#{associated_record_type}").find_by_id(associated_record_id)

Is there a way to do this dynamically without using an eval?

record =
associated_record_type.classify.constantize.find_by_id(associated_record_id)

Actually, you might be better off with just .constantize - depends
what precise value you have in “associated_record_type”

record =
associated_record_type.constantize.find_by_id(associated_record_id)

http://api.rubyonrails.org/v2.3.8/classes/ActiveSupport/CoreExtensions/String/Inflections.html

On Tue, May 3, 2011 at 2:33 PM, Michael P. [email protected]
wrote:

Actually, you might be better off with just .constantize - depends
what precise value you have in “associated_record_type”

Michael, thats just what I was looking for. It is a polymorphic
situation
and the value in the field is a string, so works out perfect. Thanks!

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