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

A has_many Relationship within a Single Model in Rails

Here are a couple methods for dealing with uni-directional many-to-many associations in Rails.

Apr 04, 2015

How we apply the Rails Doctrine to the Jamstack

Just like omakase sushi is solely the chef's choice, the biggest benefit to any framework is when it makes (good) decisions for you.

Oct 01, 2020

Connect to a Remote MySQL Database in Rails

Using a remote database with rails is useful for collaborating on projects or for keeping all your data in one place. Here's how to get it set up from scratch.

Mar 09, 2015