Reflection additions in Ruby 3

suggest change

Ruby has always let a program look at itself: obj.methods, obj.class, Klass.ancestors, instance_variables and friends are covered in Introspection and View an object's methods. The Ruby 3.x releases filled in several gaps that used to need ObjectSpace scans or string parsing:

Method Added in What it answers
attr_accessor / attr_reader / attr_writer return symbols 3.0 lets you write private attr_accessor :x
Module#private / public / protected return their arguments 3.1 lets you chain visibility calls
Class#subclasses 3.1 which classes directly inherit from this one?
Class#attached_object 3.2 which object does this singleton class belong to?
Module#refinements, Module.used_refinements 3.2 which refinements does a module define / are active here?
Module#undefined_instance_methods 3.2 which methods were removed with undef_method?
Module#const_added hook 3.2 called every time a constant is defined in a module
Refinement#target 3.3 which class does a refinement refine?
Module#set_temporary_name 3.3 give an anonymous class a readable name
ObjectSpace::WeakKeyMap 3.3 attach data to classes (or any object) without keeping them alive

All the output below comes from Ruby 4.0.7 (RubyInstaller, x64-mingw-ucrt). Everything works the same on Ruby 3.3 and later. For the older methods, the version they appeared in is noted next to them.

Class#subclasses (3.1)

superclass has always told you a class's parent. Ruby 3.1 added the other direction: subclasses returns the classes that inherit directly from the receiver.

class Shape; end
class Circle < Shape; end
class Square < Shape; end
class RoundedSquare < Square; end

p Shape.subclasses
p Square.subclasses
p RoundedSquare.subclasses
p Shape.superclass
p Integer.subclasses
p Numeric.subclasses.sort_by(&:name)
p Exception.subclasses.size
$ ruby subclasses.rb
[Square, Circle]
[RoundedSquare]
[]
Object
[]
[Complex, Float, Integer, Rational]
9

Things to know:

Getting all descendants

class Shape; end
class Circle < Shape; end
class Square < Shape; end
class RoundedSquare < Square; end

old_way = ObjectSpace.each_object(Shape.singleton_class).reject { |k| k == Shape }
p old_way.sort_by(&:name)

def descendants(klass) = klass.subclasses.flat_map { |k| [k, *descendants(k)] }
p descendants(Shape)

p ObjectSpace.each_object(Class).count { |k| k < Exception }
p ObjectSpace.count_objects.slice(:T_CLASS, :T_MODULE, :T_STRING).keys
$ ruby descendants.rb
[Circle, RoundedSquare, Square]
[Square, RoundedSquare, Circle]
187
[:T_CLASS, :T_MODULE, :T_STRING]

Before 3.1 the usual trick was ObjectSpace.each_object(Shape.singleton_class). Every subclass of Shape is an instance of Shape's singleton class (or of a subclass of it), so that call finds all descendants. It works, but it walks the whole heap. subclasses reads a list Ruby already keeps for each class, so it's much cheaper.

ObjectSpace.each_object(Class) is still the tool for questions like "how many exception classes are loaded right now?". ObjectSpace.count_objects gives counts of raw object types (T_CLASS, T_STRING, ...) for memory investigations.

Subclasses can be garbage collected

The list behind subclasses holds its classes weakly. An anonymous class that nothing references any more disappears from it after GC:

class Base; end
def make = 3.times { Class.new(Base) }
make
p Base.subclasses.size
GC.start
p Base.subclasses.size
Keep = Class.new(Base)
GC.start
p Base.subclasses
$ ruby gc_subclasses.rb
3
0
[Keep]

When collection happens is up to the GC, so subclasses may still list a dead class for a while. Classes assigned to constants are referenced by the constant and stay.

Example: a plugin registry with subclasses

A common pattern is a base class whose subclasses are plugins. The old way is to register each subclass in an inherited hook and keep your own array. With subclasses the class hierarchy is the registry:

class Exporter
  def self.format_name = name.delete_suffix("Exporter").downcase

  def self.all
    subclasses.flat_map { |k| [k, *k.all] }
  end

  def self.for(format)
    all.find { |k| k.format_name == format.to_s } or
      raise ArgumentError, "no exporter for #{format.inspect}"
  end

  def self.formats = all.map(&:format_name).sort

  def initialize(rows) = @rows = rows
end

class CsvExporter < Exporter
  def render = @rows.map { |r| r.join(",") }.join("\n")
end

class TsvExporter < CsvExporter
  def render = @rows.map { |r| r.join("\t") }.join("\n")
end

class JsonExporter < Exporter
  def render
    require "json"
    JSON.generate(@rows)
  end
end

rows = [["id", "name"], [1, "Ann"]]
p Exporter.formats
puts Exporter.for(:csv).new(rows).render
puts Exporter.for("json").new(rows).render
p Exporter.for(:tsv).superclass
begin
  Exporter.for(:xml)
rescue ArgumentError => e
  puts e.message
end
$ ruby registry.rb
["csv", "json", "tsv"]
id,name
1,Ann
[["id","name"],[1,"Ann"]]
CsvExporter
no exporter for :xml

Exporter.all recurses, so TsvExporter (a grandchild) is found too. Because self.all is inherited, CsvExporter.all returns just [TsvExporter].

There's a catch: a plugin only shows up after its file has been loaded. With Zeitwerk or other autoloaders, classes that haven't been referenced yet don't exist, so subclasses won't list them. Eager-load the plugin directory first, or keep an explicit registry.

Class#attached_object (3.2)

Every object can have a singleton class, the hidden class that holds its singleton methods (see Singleton Class). singleton_class goes from an object to its singleton class. attached_object goes back:

class User
  def self.find(id) = new
end
meta = User.singleton_class
p meta
p meta.attached_object
p meta.attached_object.equal?(User)

str = +"hello"
p str.singleton_class.attached_object

begin
  String.attached_object
rescue TypeError => e
  puts "#{e.class}: #{e.message}"
end

p User.singleton_class.singleton_class.attached_object
p meta.singleton_class?
p User.singleton_class?
$ ruby attached.rb
#<Class:User>
User
true
"hello"
TypeError: 'String' is not a singleton class
#<Class:User>
true
false

Before 3.2 people parsed meta.inspect ("#<Class:User>") or searched ObjectSpace to find the owner. That breaks for anonymous classes and objects with custom inspect. Use singleton_class? to check first, since attached_object raises TypeError on a normal class.

This is mostly useful in code that receives a class from a hook. For example, method_added and singleton_method_added hooks, or tools that walk ancestors and find #<Class:...> entries in them.

Module#set_temporary_name (3.3)

Classes created with Class.new have no name until they're assigned to a constant, so they print as #<Class:0x...>. That makes error messages and logs from DSLs hard to read. set_temporary_name gives such a class a name that's used until it gets a real one:

klass = Class.new
p klass
p klass.name
klass.set_temporary_name("fake_name")
p klass
p klass.name
p klass.new
Point = klass
p klass.name
begin
  klass.set_temporary_name("other")
rescue RuntimeError => e
  puts "#{e.class}: #{e.message}"
end
m = Module.new
begin
  m.set_temporary_name("Kernel")
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
m.set_temporary_name("<plugin:csv>")
p m
m.set_temporary_name(nil)
p m
$ ruby temp_name.rb
#<Class:0x0000029a1bdd1230>
nil
fake_name
"fake_name"
#<fake_name:0x0000029a1bc6b328>
"Point"
RuntimeError: can't change permanent name
ArgumentError: the temporary name must not be a constant path to avoid confusion
<plugin:csv>
#<Module:0x0000029a1bdd06f0>

The rules:

Here's how a class factory (see Dynamic class creation) can use it. Constants nested in the class pick up the temporary name too:

def record(table, *columns)
  Class.new do
    set_temporary_name("record(#{table})")
    attr_reader(*columns)
    define_method(:initialize) do |**attrs|
      columns.each { |c| instance_variable_set("@#{c}", attrs.fetch(c)) }
    end
    const_set(:COLUMNS, columns.freeze)
    const_set(:Error, Class.new(StandardError))
  end
end

users = record(:users, :id, :email)
u = users.new(id: 1, email: "a@example.com")
p users
p u
p users::COLUMNS
p users::Error
begin
  users.new(id: 2)
rescue KeyError => e
  puts "#{e.class}: #{e.message}"
end
User = users
p User::Error
p u
$ ruby record.rb
record(users)
#<record(users):0x000002a0533fa7f0 @id=1, @email="a@example.com">
[:id, :email]
record(users)::Error
KeyError: key not found: :email
User::Error
#<User:0x000002a0533fa7f0 @id=1, @email="a@example.com">

Once the class is assigned to User, both it and the nested Error get permanent names.

Inspecting refinements (3.2, 3.3)

Refinements used to be a black box: once you wrote refine String do ... end there was no way to ask a module what it refines. Ruby 3.2 added Module#refinements and the Refinement class, and 3.3 added Refinement#target:

module TextExt
  refine String do
    def squish = split.join(" ")
  end
  refine Integer do
    def minutes = self * 60
  end
end

p TextExt.refinements
r = TextExt.refinements.first
p r.class
p r.target
p TextExt.refinements.map(&:target)
p r.instance_methods(false)
p Module.used_modules

using TextExt
p Module.used_modules
p Module.used_refinements
p "  a   b  ".squish
p 5.minutes
p r.respond_to?(:refined_class)
$ ruby refinements.rb
[#<refinement:String@TextExt>, #<refinement:Integer@TextExt>]
Refinement
String
[String, Integer]
[:squish]
[]
[TextExt]
[#<refinement:String@TextExt>, #<refinement:Integer@TextExt>]
"a b"
300
false

private and friends return their arguments (3.0, 3.1)

Before 3.0, attr_accessor returned nil. Since 3.0 the attr_* methods return the symbols of the methods they defined, so private attr_accessor :x works. Before 3.1, private :foo returned the class itself. Since 3.1, private, public, protected and module_function return what you passed them. That's what makes these one-liners work:

class Account
  p(private def secret = 42)
  p(private :secret)
  p(private attr_accessor :balance, :owner)
  p(public)
  p(protected def peer = 1)

  p private_instance_methods(false).sort
  p protected_instance_methods(false)
end
p Account.public_method_defined?(:balance)
$ ruby visibility.rb
:secret
:secret
[:balance, :balance=, :owner, :owner=]
nil
:peer
[:balance, :balance=, :owner, :owner=, :secret]
[:peer]
false

One argument comes back as itself, several come back as an array, and no arguments (the form that changes the default visibility for the following defs) return nil. private attr_accessor :balance, :owner makes all four generated methods private in one line. Before 3.0 you had to list them again in a separate private call.

Who defined this method? Method#owner and visibility

Method#owner (and UnboundMethod#owner) has been around since 1.9, but it's worth knowing together with the 3.x additions. It tells you which class or module actually holds the code that a call will run:

module Loggable
  def log(msg) = puts("[#{self.class}] #{msg}")
end

class Base
  def save = true
  private def validate = true
end

class Post < Base
  include Loggable
  def save = super && log("saved")
end

post = Post.new
p post.method(:save).owner
p post.method(:save).super_method.owner
p post.method(:log).owner
p post.method(:to_s).owner
p post.method(:save).source_location

def visibility(obj, name)
  owner = obj.method(name).owner
  if owner.public_method_defined?(name, false) then :public
  elsif owner.protected_method_defined?(name, false) then :protected
  else :private
  end
end
p visibility(post, :save)
p visibility(post, :validate)
p visibility(post, :puts)
p Post.instance_method(:validate).owner

p Post.method_defined?(:validate)
p Post.private_method_defined?(:validate)
p Post.private_method_defined?(:validate, false)
$ ruby owner.rb
Post
Base
Loggable
Kernel
["owner.rb", 12]
:public
:private
:private
Base
false
true
false

super_method walks up the chain to the method that super would call. The second argument to public_method_defined? and friends (added in 2.6) limits the check to the module itself, without its ancestors.

Ruby 3.1 added Method#public?, #private? and #protected?, but they were removed again in 3.2 (a method object's visibility depends on how it was looked up, so the answer was confusing). If you see them in 3.1-era code, use the *_method_defined? checks on owner shown above instead.

Where was it defined? const_source_location and undefined_instance_methods

Method#source_location tells you where a method was defined. Module#const_source_location (2.7) does the same for constants, and Module#undefined_instance_methods (3.2) lists methods that were removed with undef_method:

class Legacy
  def old_api = :old
  def keep = :keep
end

class Legacy
  undef_method :old_api
end

LIMIT = 10

p Legacy.undefined_instance_methods
p Legacy.new.respond_to?(:old_api)
p Object.const_source_location(:Legacy)
p Object.const_source_location("LIMIT")
p Object.const_source_location(:String)
p Object.const_source_location(:Nope)
p Legacy.instance_method(:keep).source_location
$ ruby locations.rb
[:old_api]
false
["locations.rb", 1]
["locations.rb", 10]
[]
nil
["locations.rb", 3]

The const_added hook (3.2)

Ruby had inherited, method_added and included hooks, but nothing for constants. Since 3.2, Module#const_added is called each time a constant is defined in the module, including classes and modules nested in it:

module Commands
  REGISTRY = {}
  def self.const_added(name)
    super
    value = const_get(name)
    REGISTRY[name.to_s.downcase] = value if value.is_a?(Class)
    puts "const_added: #{name}"
  end

  class Build; end
  class Deploy; end
  VERSION = "1.0"
end
p Commands::REGISTRY
$ ruby const_added.rb
const_added: Build
const_added: Deploy
const_added: VERSION
{"build" => Commands::Build, "deploy" => Commands::Deploy}

The hook gets the constant name as a symbol. REGISTRY itself doesn't trigger it, because the hook isn't defined yet when that line runs. This is another way to build a registry, keyed by namespace instead of by superclass.

ObjectSpace::WeakKeyMap (3.3)

Reflection code often wants to cache something per class, like a computed schema or a list of methods. A plain Hash keyed by class keeps anonymous classes alive forever. ObjectSpace::WeakKeyMap holds its keys weakly and compares them with eql?/hash like a normal hash:

META = ObjectSpace::WeakKeyMap.new

def describe(klass)
  META[klass] ||= {
    name: klass.name || klass.inspect,
    methods: klass.public_instance_methods(false).sort,
  }
end

class Invoice
  def total = 0
  def due_on = nil
end

p describe(Invoice)
p META.key?(Invoice)
p META.getkey(Invoice)
tmp = Class.new { def run = 1 }.tap { _1.set_temporary_name("tmp_job") }
p describe(tmp)
p META.inspect
$ ruby weak_map.rb
{name: "Invoice", methods: [:due_on, :total]}
true
Invoice
{name: "tmp_job", methods: [:run]}
"#<ObjectSpace::WeakKeyMap:0x000001c8a2d6b3b8 size=2>"

When tmp is garbage collected, its entry disappears from the map. WeakKeyMap supports [], []=, key?, getkey, delete and clear, but not iteration, because entries can vanish at any time. The older ObjectSpace::WeakMap compares keys by identity and holds both keys and values weakly.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents