Module: Nesting

Defined in:
lib/nesting.rb

Class Method Summary collapse

Class Method Details

.of(mod) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/nesting.rb', line 3

def of(mod)
  if nonmodule?(mod)
    raise TypeError, 'mod is not a class or module'
  end

  level = 0

  # Special case Object as it's the namespace of all classes.
  return level if mod == Object

  level = if mod.name
            mod.name.split('::').count
          else
            -1 # Probably an anonymous module.
          end

  level
end

.parents(mod) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/nesting.rb', line 22

def parents(mod)
  if nonmodule?(mod)
    raise TypeError, 'mod is not a class or module'
  end

  parents = []

  return nil if mod == Object

  if mod.name
    mod.name.split('::')[0..-2].inject(Object) do |parent, child|
      const = parent.const_get(child)
      parents << const
      const
    end
    parents.reverse! << Object
  else
    parents = nil # Probably an anonymous module.
  end

  parents
end