If I have a class like the following, how do I tell when an ancestor is a class vs. a 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"
]
I would like to be able to do something like this:
ancestor_names.each do |name|
if class?(name)
puts "#{name} is a Class"
elsif module?(name)
puts "#{name} is a Module"
end
end
or...
SubGroup.ancestor_classes #=> only the classes in the tree
SubGroup.ancestor_modules #=> only the modules in the tree
It boils down to, how do you check if an object is a class or module?
Well, that is what included_modules
is for, so what you're probably looking for is:
SubGroup.included_modules #=> module ancestors
SubGroup.ancestors - SubGroup.included_modules #=> class ancestors
Or, with a helper method:
class Class
def ancestor_classes
ancestors - included_modules
end
end
SubGroup.included_modules #=> module ancestors
SubGroup.ancestor_classes #=> class ancestors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With