0

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

3
  • You may always use is_a? to test for a certain type. Commented Mar 9, 2016 at 9:52
  • The question always is: why do you need it? If you are planning to use it for forking your flow it will be a serious architectural error (breaking Demeter law) which you will need to pay for later. Commented Mar 9, 2016 at 9:58
  • 1
    Possible duplicate of How do I get the name of a Ruby class? Commented Mar 9, 2016 at 10:22

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

another way to do it is @commentable.class.to_s.underscore
@commentable.class.model_name.singular is a rails way of doing it.
0

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. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.