gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:38:59 26 4
gpt4 key购买 nike

如果我有一个像下面这样的类,我如何判断祖先是类还是模块?

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

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

最佳答案

嗯,就是这样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

关于ruby - 判断祖先是Ruby中的类还是模块的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com