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

Use Slack For Rails Error Notification

Post a message to one of your Slack channels when your Rails app encounters a 500 error.

Dec 22, 2015

3 Reasons Why Turbolinks Is Not Worth The Effort

Turbolinks is a great idea in theory, but it comes with enough problems to offset its benefits.

Mar 15, 2016

Big Oops: Just a Few (Old) Notifications

I've learned a few things the hard way. How to properly use Active Record callbacks with Ruby on Rails is one of those things.

Jun 15, 2020