2009-11-28 38 views
15

我如何從一個模塊獲取模塊包含的類的類名獲取類的名字嗎?從模塊

module ActMethods 
    def some_method(*attr_names) 
    cls = self.class # this doesn't work 
    end 
end 

我如何進入cls變量加載該模塊的類的名稱?

+0

應該是工作!可能是你需要self.class.name – khelll 2009-11-29 04:34:14

+0

請注意,如果類以匿名方式進行擴展,則打印出self.class或self.class.name將返回空白,這可能會造成混淆。這種情況下,檢查self.class.superclass也是很好的做法。 – 2011-08-12 09:17:51

+0

'self.class'不適合我。 'self.class.name'返回「Module」。我認爲這與我的模塊包含的類繼承自ActiveRecord :: Base(Rails 3.2.8)的事實有關,但我不確定這是干涉的原因或方式。 – 2012-10-14 13:40:51

回答

9

self.class不會讓你的類中的方法被調用的對象。假設這個模塊被包含在一個類中,那麼它就是包含該模塊或其子類的類。如果你真的只想要這個名字,你可以用self.class.name代替。

如果您使用該模塊擴展了一個類,並且想要獲得該類,則只需執行cls = self(或cls = name,如果要將該類的名稱作爲字符串)。

如果上述的幫助,你應該清楚你想要什麼。

1

爲我工作。正如sepp說你必須包括它才能工作。

module ActMethods 
    def some_method(*attr_names) 
    cls = self.class # this doesn't work 
    puts cls 
    end 
end 

class Boh 
    include ActMethods 
end 

b = Boh.new 
b.some_method 
6

如果self是不是出於某種原因的選項,替代可能是ancestorshttp://ruby-doc.org/core-2.0/Module.html#method-i-ancestors

# rails concern example: 

module Foo 
    extend ActiveSupport::Concern 

    included do 
    p "Wooo hoo, it's #{top_ancestor_class}" 
    end 

    module ClassMethods 
    def top_ancestor_class 
     ancestors.first 
    end 
    end 
end 

class Event < ActiveRecord::Base 
    include Foo 
end 

#=> Woo hoo, it's Event(....) 
+0

BTW更多信息在我的文章中http://www.eq8.eu/blogs/13-ruby-ancestors-descendants-和其他惱人的親屬 – equivalent8 2015-04-23 22:17:31

1

PS:對於一般情況下的答案,看到sepp2k的答案。

如果你只包括在控制器模塊,你可能要考慮使用controller_name.classify得到相應的模型的名稱。例如:

>> ArticlesController.controller_name.classify 
=> "Article" 

從那裏你可以得到實際的類(如果你想),通過對結果調用.constantize