Class: Inspector

Inherits:
Object
  • Object
show all
Defined in:
lib/rdb/inspector.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInspector

Returns a new instance of Inspector.



4
5
6
# File 'lib/rdb/inspector.rb', line 4

def initialize
  @seen_ids = Set.new
end

Class Method Details

.inspect(obj) ⇒ Object



8
9
10
# File 'lib/rdb/inspector.rb', line 8

def self.inspect(obj)
  Inspector.new.inspect(obj)
end

Instance Method Details

#inspect(obj) ⇒ Object



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
# File 'lib/rdb/inspector.rb', line 12

def inspect(obj)
  if !@seen_ids.add?(obj.object_id)
    return "(circular reference)"
  end

  # Range, Regex, Block, Proc, lambda, Thread, Set, ...
  case obj
  when Class
    return { class: obj.class.name, content: obj.name }
  when Fixnum, Float, TrueClass, FalseClass, NilClass, String, Symbol
    return { class: obj.class.name, content: obj }
  when Array
    return { class: obj.class.name, content: obj.map { |x| inspect(x) } }
  when Hash
    inspected = []
    obj.each do |k, v|
      inspected << [inspect(k), inspect(v)]
    end
    return { class: obj.class.name, content: inspected }
  end

  vars = Hash[obj.instance_variables.map { |var|
    [var, inspect(obj.instance_variable_get(var))]
  }]

  return {
    class: obj.class.name,
    content: vars
  }
end