Skip to content

Instantly share code, notes, and snippets.

@casperisfine
Created December 9, 2022 14:05
Show Gist options
  • Save casperisfine/9e00cfb1dd7b36eabc2841431b832ee6 to your computer and use it in GitHub Desktop.
Save casperisfine/9e00cfb1dd7b36eabc2841431b832ee6 to your computer and use it in GitHub Desktop.
require 'objspace'
require 'json'
class Foo
class_eval <<~RUBY
def initialize
#{21.times.map { |i| "@attr_#{i} = #{i}" }.join("\n")}
end
RUBY
def define_ivars(num, offset: 0, suffix: '')
num.times do |i|
instance_variable_set(:"@attr_#{i + offset + 1}#{suffix}", i + offset + 1)
end
end
end
2.times do |iter|
puts "=" * 40
obj = Foo.new
p obj
if iter == 1
obj.define_ivars(7, suffix: "extra")
obj.remove_instance_variable(:@attr_20)
obj.define_ivars(9, suffix: "extra")
end
shapes = ObjectSpace.dump_shapes(output: :string)
$shapes = shapes.lines.map { |l| JSON.parse(l) }.each_with_object({}) { |s, h| h[s["id"]] = s }
def shape_ancestors(s)
if s["parent_id"]
shape_ancestors($shapes[s["parent_id"]])
end
p s
end
puts
shape_id = JSON.parse(ObjectSpace.dump(obj))["shape_id"]
shape_ancestors($shapes[shape_id])
puts
puts ObjectSpace.dump(obj)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment