Module: MoreCoreExtensions::ClassHierarchy

Defined in:
lib/more_core_extensions/core_ext/class/hierarchy.rb

Instance Method Summary collapse

Instance Method Details

#descendant_get(desc_name) ⇒ Object

Returns the descendant with a given name

require 'socket'
IO.descendant_get("IO")
# => IO
IO.descendant_get("BasicSocket")
# => BasicSocket
IO.descendant_get("IPSocket")
# => IPSocket

Raises:

  • (ArgumentError)


17
18
19
20
21
22
# File 'lib/more_core_extensions/core_ext/class/hierarchy.rb', line 17

def descendant_get(desc_name)
  return self if desc_name == name || desc_name.nil?
  klass = descendants.find { |desc| desc.name == desc_name }
  raise ArgumentError, "#{desc_name} is not a descendant of #{name}" unless klass
  klass
end

#hierarchy(&block) ⇒ Object

Returns a tree-like Hash structure of all descendants.

If a block is passed, that block is used to format the keys of the hierarchy

require 'socket'
IO.hierarchy
# => {BasicSocket=>
#      {Socket=>{},
#       IPSocket=>{TCPSocket=>{TCPServer=>{}}, UDPSocket=>{}},
#       UNIXSocket=>{UNIXServer=>{}}},
#     File=>{}}

IO.hierarchy(&:name)
# => {"BasicSocket"=>
#      {"Socket"=>{},
#       "IPSocket"=>{"TCPSocket"=>{"TCPServer"=>{}}, "UDPSocket"=>{}},
#       "UNIXSocket"=>{"UNIXServer"=>{}}},
#     "File"=>{}}


42
43
44
45
46
47
# File 'lib/more_core_extensions/core_ext/class/hierarchy.rb', line 42

def hierarchy(&block)
  subclasses.each_with_object({}) do |k, h|
    key = block ? yield(k) : k
    h[key] = k.hierarchy(&block)
  end
end

#leaf_subclassesObject

Returns an Array of all descendants which have no subclasses

require 'socket'
BasicSocket.leaf_subclasses
# => [Socket, TCPServer, UDPSocket, UNIXServer]


63
64
65
# File 'lib/more_core_extensions/core_ext/class/hierarchy.rb', line 63

def leaf_subclasses
  descendants.select { |d| d.subclasses.empty? }
end

#lineageObject

Returns an Array of all superclasses.

require 'socket'
TCPServer.lineage
# => [TCPSocket, IPSocket, BasicSocket, IO, Object, BasicObject]


54
55
56
# File 'lib/more_core_extensions/core_ext/class/hierarchy.rb', line 54

def lineage
  superclass.nil? ? [] : superclass.lineage.unshift(superclass)
end