Create an object of a type (class) stored in a string

July 4, 2009 at 10:15 pm Leave a comment

So, you have a class of object stored in a string, and you want to create an object of that class. You cannot assign a type of an object directly (by say @myvar.class = xxx), and the class conversions are limited to the basic built-in classes like to_s, etc. But you can use this trick:

@classtype = "Artist" 
@myvar = Kernel.const_get(@classtype).find(@id)

Another (quite similar) option is to use the Rails constantize method (that in turn uses const_get). This is how for example acts_as_commentable plugin can provide a method to get the commentable object back by passing the type and id of it:

  def self.find_commentable(commentable_str, commentable_id)
    commentable_str.constantize.find(commentable_id)
  end
Advertisements

Entry filed under: Uncategorized. Tags: .

My Ruby on Rails dev environment Voting plugin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent posts

Starting to learn Rails?

Kindle

Get Kindle - the best e-book reader, that I personally use, and the only one that you can read on the beach - very useful: Kindle Wireless Reading Device (6" Display, Global Wireless, Latest Generation)

%d bloggers like this: