Saturday, May 28, 2011

Convert string to a class/model

This post is related to how to convert string to class ( model ). I came across this situation while migrating one of my organization's project on rails 3.

Many times we came across a situation where we need to convert a string to respective class or model. So that we can call methods on it. Generally to handle this situation new rails developers use case statement like this,

case class_name_string
when 'Account'
object = Account.find(id)

when 'Contact'
object = Contact.find(id)

when 'Opportunity'
object = Opportunity.find(id)

when 'Campaign'
object = Campaign.find(id)

when 'Model1'
object = Model1.find(id)

when 'Model2'
object = Model2.find(id)
:
:
:
:
when 'Modeln'
object = Modeln.find(id]) 
end

This can be actually done pretty easily by using constantize in only one line

class_name_string.constantize.find(id)

No comments:

Post a Comment