告诉祖先是Ruby中的Class还是Module的方法?

前端之家收集整理的这篇文章主要介绍了告诉祖先是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

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

解决方法

那么这就是 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
原文链接:https://www.f2er.com/ruby/271901.html

猜你在找的Ruby相关文章