Sha256: e5816ade1e42a9baccdf5f7061ee64f62296a42d5013ec7c308825f48ff8d8fe

Contents?: true

Size: 1019 Bytes

Versions: 1

Compression:

Stored size: 1019 Bytes

Contents

require 'set'

class Inspector
  def initialize
    @seen_ids = Set.new
  end

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

  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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rdb-0.0.1 lib/rdb/inspector.rb