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

July 4, 2009

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

Entry Filed under: Uncategorized. Tags: .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent posts

Starting to learn Rails?

Archive

Recent comments

Ryan H on Installing Rails on Windows (3…
gogetakame on Installing Rails on Windows (3…
gogetakame on Installing Rails on Windows (3…
allaboutruby on Installing Rails on Windows (3…
Harsha on Installing Rails on Windows (3…