Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

ruby - How do I tell what modules have been mixed into a class?

I have a class that has a number of modules that are mixed in with it based on some runtime criteria.

I want to be able to get a list of what modules have been mixed into this class. How can you do that?

UPDATE

So when I said class I meant object as it is the object that is being extended at runtime using:

obj.extend(MyModule)

obj.included_modules and obj.ancestors don't exist so you can't get the modules that have been mixed in from there.

question from:https://stackoverflow.com/questions/1328068/how-do-i-tell-what-modules-have-been-mixed-into-a-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

MyClass.ancestors.select {|o| o.class == Module }

for example:

>> Array.ancestors.select {|o| o.class == Module}
=> [Enumerable, Kernel]

UPDATE

To get the modules mixed into an object instance at runtime you'll need to retrieve the eigenclass of the instance. There is no clean way to do this in Ruby, but a reasonably common idiom is the following:

(class << obj; self; end).included_modules

If you find yourself using this a lot, you can make it generally available:

module Kernel
  def eigenclass
    class << self
      self
    end
  end
end

and the solution is then:

obj.eigenclass.included_modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...