How do I get the name of a Ruby class?

后端 未结 5 774
青春惊慌失措
青春惊慌失措 2020-12-02 04:23

How can I get the class name from an ActiveRecord object?

I have:

result = User.find(1)

I tried:

result.class
# =&g         


        
相关标签:
5条回答
  • 2020-12-02 05:07

    In my case when I use something like result.class.name I got something like Module1::class_name. But if we only want class_name, use

    result.class.table_name.singularize

    0 讨论(0)
  • 2020-12-02 05:11

    If you want to get a class name from inside a class method, class.name or self.class.name won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

    module Foo
      class Bar
        def self.say_name
          puts "I'm a #{name}!"
        end
      end
    end
    
    Foo::Bar.say_name
    

    output:

    I'm a Foo::Bar!
    
    0 讨论(0)
  • 2020-12-02 05:24

    Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

    If you use Rails (ActiveSupport):

    result.class.name.demodulize
    

    If you use POR (plain-ol-Ruby):

    result.class.name.split('::').last
    
    0 讨论(0)
  • 2020-12-02 05:26

    You want to call .name on the object's class:

    result.class.name
    
    0 讨论(0)
  • 2020-12-02 05:28

    Both result.class.to_s and result.class.name work.

    0 讨论(0)
提交回复
热议问题