Raymond R
Raymond R

Reputation: 1348

How to get the class name from an instance variable in Rails?

If I have @commentable, which could either be a Post or Article, can I extract the model name from the instance variable?

Upvotes: 0

Views: 2343

Answers (2)

Arslan Ali
Arslan Ali

Reputation: 17802

You can use:

@commentable.class.name

But here is a gotcha. If the name of a class is like this ActiveRecord::Base i.e. it contains a module as well, you can call demodulize to get only the class name.

@instance_variable.class.name.demodulize # when the class name contains any module.

Upvotes: 0

Alexander Presber
Alexander Presber

Reputation: 6635

Use @commentable.class.name to find out the variable's class name.

Upvotes: 3

Related Questions