判断祖先是Ruby中的类还是模块的方法?

时间:2010-09-11 23:30:54

标签: ruby class module

如果我有类似以下的课程,我如何判断祖先是一个班级还是一个模块?

ActiveRecord::Base.send(:include, SomeLibrary)

class Group < ActiveRecord::Base
  include SomeLibrary::Core
end

class SubGroup < Group

end

ancestor_names = SubGroup.ancestors.map(&:name)
puts ancestor_names.inspect
  #=> [
  "SubGroup", "SomeLibrary::Core::InstanceMethods", "SomeLibrary::Core", 
  "Group", "ActiveRecord::Base", "SomeLibrary", "ActiveRecord::Aggregations", 
  "ActiveRecord::Transactions", "ActiveRecord::Reflection", "ActiveRecord::Batches", 
  "ActiveRecord::Calculations", "ActiveRecord::Serialization", "ActiveRecord::AutosaveAssociation", 
  "ActiveRecord::NestedAttributes", "ActiveRecord::Associations", "ActiveRecord::AssociationPreload", 
  "ActiveRecord::NamedScope", "ActiveRecord::Callbacks", "ActiveRecord::Observing", 
  "ActiveRecord::Timestamp", "ActiveRecord::Dirty", "ActiveRecord::AttributeMethods", 
  "ActiveRecord::Locking::Optimistic", "ActiveRecord::Locking::Pessimistic", 
  "ActiveSupport::Callbacks", "ActiveRecord::Validations", "Object", "Mocha::ObjectMethods", 
  "JSON::Pure::Generator::GeneratorMethods::Object", "ActiveSupport::Dependencies::Loadable", 
  "Base64::Deprecated", "Base64", "PP::ObjectMixin", "Kernel"
]

我希望能够做到这样的事情:

ancestor_names.each do |name|
  if class?(name)
    puts "#{name} is a Class"
  elsif module?(name)
    puts "#{name} is a Module"
  end
end

...或

SubGroup.ancestor_classes #=> only the classes in the tree
SubGroup.ancestor_modules #=> only the modules in the tree

归结为,如何检查对象是类还是模块?

3 个答案:

答案 0 :(得分:13)

嗯,这就是included_modules的用途,所以您可能正在寻找的是:

SubGroup.included_modules                       #=> module ancestors
SubGroup.ancestors - SubGroup.included_modules  #=> class ancestors

或者,使用辅助方法:

class Class
  def ancestor_classes
    ancestors - included_modules
  end
end

SubGroup.included_modules  #=> module ancestors
SubGroup.ancestor_classes  #=> class ancestors

答案 1 :(得分:11)

使用Object#instance_of?

Object.instance_of? Class  # => true
Object.instance_of? Module # => false
Kernel.instance_of? Class  # => false
Kernel.instance_of? Module # => true

答案 2 :(得分:0)

以上答案已经足够了。下面的内容也可能会有所帮助。

pp SubGroup.ancestors.map {|c| c.instance_of?(Class) ? "CLASS: #{c}" : "MODULE: #{c}" }