Bobochka
6/3/2015 - 3:58 PM

Ruby object space

Ruby object space

# particular type counts
ObjectSpace.each_object(ActiveRecord::Base).count

# all objects counts (ruby types)
ObjectSpace.count_objects

# all object counts (program types)
counts = {}
counts.default = 0
ObjectSpace.each_object(Object) { |o| counts[o.class] += 1 }
counts.sort_by { |_, value| -1 * value }.take(10)

# destructor
class MyClass
  attr_reader :name
  def initialize(name)
    @name = name
    ObjectSpace.define_finalizer(self,                MyClass.finalize(name))
  end

  def self.finalize name
    proc { puts "#{name} Going Down!"}
  end

end

# run block for each object
ObjectSpace.each_object(MyClass) {|obj| p obj.name}