1 2 3 4 5 6 7 8 9 10 11 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
# frozen_string_literal: true
# This private class encapsulates pairs (mod, cname).
#
# Objects represent the constant `cname` in the class or module object `mod`,
# and have API to manage them. Examples:
#
# cref.path
# cref.set(value)
# cref.get
#
# The constant may or may not exist in `mod`.
class Zeitwerk::Cref
require_relative "cref/map"
include Zeitwerk::RealModName
#: Module
attr_reader :mod
#: Symbol
attr_reader :cname
# The type of the first argument is Module because Class < Module, class
# objects are also valid.
#
#: (Module, Symbol) -> void
def initialize(mod, cname)
@mod = mod
@cname = cname
@path = nil
end
#: () -> String
def path
@path ||= Object == @mod ? @cname.name : "#{real_mod_name(@mod)}::#{@cname.name}".freeze
end
alias to_s path
#: () -> String?
def autoload?
@mod.autoload?(@cname, false)
end
#: (String) -> nil
def autoload(abspath)
@mod.autoload(@cname, abspath)
end
#: () -> bool
def defined?
@mod.const_defined?(@cname, false)
end
#: (top) -> top
def set(value)
@mod.const_set(@cname, value)
end
#: () -> top ! NameError
def get
@mod.const_get(@cname, false)
end
#: () -> void ! NameError
def remove
@mod.__send__(:remove_const, @cname)
end
end
|