Метод определения того, является ли предок классом или модулем в Ruby?

Если у меня есть класс, подобный следующему, как мне узнать, когда предком является класс, а не класс модуль?

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

Это сводится к следующему: как проверить, является ли объект классом или модулем?

13
задан Lance Pollard 11 September 2010 в 23:30
поделиться