Class: Introspect::Contents

Inherits:
Object
  • Object
show all
Defined in:
lib/introspect/contents.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Contents

Returns a new instance of Contents.



6
7
8
# File 'lib/introspect/contents.rb', line 6

def initialize object
  @object = object
end

Class Method Details

.contents(object, arg = nil) ⇒ Object



2
3
4
# File 'lib/introspect/contents.rb', line 2

def self.contents object, arg = nil
  self.new(object).contents arg
end

Instance Method Details

#contents(depth = 0) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/introspect/contents.rb', line 10

def contents depth = 0
  depth = 0 if depth.nil?

  if @object.kind_of?(Module) && ![Object, Module, Class, BasicObject, Kernel].include?(@object)
    @ancestors = @object.ancestors
    @ancestors.shift

    @constants = []
    @object.constants.sort.each do |c|
      object = @object.const_get(c)

      if object.respond_to?(:contents) && (depth == 0 || depth > 1) then
        @constants << object.contents(depth == 0 ? 0 : depth - 1)
      else
        @constants << nameof(object)
      end
    end

    @methods = []
    @object.methods(false).each do |m|
      @methods << @object.method(m)
    end

    @instance_methods = []
    @object.instance_methods(false).each do |m|
      @instance_methods << @object.instance_method(m)
    end
  else
    @ancestors = @object.class.ancestors
  end

  structure = Hash.new
  structure[:class] = @object.class
  structure[:ancestors] = @ancestors unless @ancestors.nil? || @ancestors.empty?
  structure[:constants] = @constants unless @constants.nil? || @constants.empty?
  structure[:methods] = @methods unless @methods.nil? || @methods.empty?
  structure[:instance_methods] = @instance_methods unless @instance_methods.nil? || @instance_methods.empty?

  {nameof(@object) => structure}
end

#nameof(obj) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/introspect/contents.rb', line 51

def nameof obj
  if obj.kind_of? Module
    obj.methods(false).include?(:inspect) ? obj.name : obj
  else
    obj
  end
end