Nếu tôi có một lớp học như sau, làm thế nào để tôi biết khi nào một tổ tiên là một lớp so với một mô-đun?Phương pháp để biết tổ tiên là một Lớp hoặc Mô-đun trong 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"
]
Tôi muốn để có thể làm điều gì đó như thế này:
ancestor_names.each do |name|
if class?(name)
puts "#{name} is a Class"
elsif module?(name)
puts "#{name} is a Module"
end
end
hoặc ...
SubGroup.ancestor_classes #=> only the classes in the tree
SubGroup.ancestor_modules #=> only the modules in the tree
Nó nắm để, làm thế nào để bạn kiểm tra xem một đối tượng là một lớp học hoặc mô-đun?