Home

Instantiate a Class from a String in Rails

Rails classes need to be called dynamically sometimes. Learn how to do it using the constantize inflector.

Sometimes you want your class names to be dynamic. Rails has a nice constantize inflector that makes this easy.

In the simplest of examples, let's just say you have a "post" string and you want to load the Post class from it. Something like the following should work great.

str = "post"
new_class_instance = str.constantize.new

We can get a little wild. Let's say you have a multi-word string and want to constantize and then instantiate it.

str = "posts controller"
new_class_instance = str.titleize.gsub(/\ /, '').constantize.new

Essentially, this just shows you want a properly-cased string (the string equivalent of the class name) before you call constantize.

Let's Connect

Keep Reading

Bi-Directional has_and_belongs_to_many on a Single Model in Rails

Bi-directional HABTM relationships are easy in Rails, but when you need to do it on a single model, that's when it gets tricky. Here's one approach.

May 04, 2015

Order Rails Query by Virtual Attribute

Rails' scopes don't work well with virtual attributes since they resolve to a SQL query. Instead you can throw them in an array and then sort by a virtual attribute.

Oct 22, 2014

Convert PDF to Image with Dragonfly and Rails

Converting a PDF to an image using Rails and Dragonfly is actually quite simple. Check it out.

Jan 06, 2015