Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to tell if ancestor is a Class or Module in Ruby?

Tags:

module

class

ruby

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?

like image 489
Lance Avatar asked Sep 11 '10 23:09

Lance


1 Answers

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
like image 141
molf Avatar answered Oct 22 '22 14:10

molf