类 Module
Module 是方法和常量的集合。模块中的方法可以是实例方法或模块方法。当模块被包含时,实例方法会作为类中的方法出现,而模块方法则不会。相反,模块方法可以在不创建封装对象的情况下调用,而实例方法则不能。(请参阅 Module#module_function。)
在下面的描述中,参数sym 指的是一个符号,它是一个带引号的字符串或一个 Symbol(例如 :name)。
module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E] Mod.instance_methods #=> [:meth]
公共类方法
源代码
static VALUE
rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE klass;
VALUE cbase = 0;
void *data = 0;
if (argc > 0 || mod != rb_cModule) {
return rb_mod_constants(argc, argv, mod);
}
while (cref) {
klass = CREF_CLASS(cref);
if (!CREF_PUSHED_BY_EVAL(cref) &&
!NIL_P(klass)) {
data = rb_mod_const_at(CREF_CLASS(cref), data);
if (!cbase) {
cbase = klass;
}
}
cref = CREF_NEXT(cref);
}
if (cbase) {
data = rb_mod_const_of(cbase, data);
}
return rb_const_list(data);
}
在第一种形式中,返回从调用点可访问的所有常量的名称数组。此列表包括在全局范围内定义的所有模块和类的名称。
Module.constants.first(4) # => [:ARGF, :ARGV, :ArgumentError, :Array] Module.constants.include?(:SEEK_SET) # => false class IO Module.constants.include?(:SEEK_SET) # => true end
第二种形式调用实例方法 constants。
源代码
static VALUE
rb_mod_nesting(VALUE _)
{
VALUE ary = rb_ary_new();
const rb_cref_t *cref = rb_vm_cref();
while (cref && CREF_NEXT(cref)) {
VALUE klass = CREF_CLASS(cref);
if (!CREF_PUSHED_BY_EVAL(cref) &&
!NIL_P(klass)) {
rb_ary_push(ary, klass);
}
cref = CREF_NEXT(cref);
}
return ary;
}
返回在调用点嵌套的 Modules 列表。
module M1 module M2 $a = Module.nesting end end $a #=> [M1::M2, M1] $a[0].name #=> "M1::M2"
源代码
static VALUE
rb_mod_initialize(VALUE module)
{
return rb_mod_initialize_exec(module);
}
创建一个新的匿名模块。如果给定一个代码块,它将被传递给模块对象,并且该代码块将在该模块的上下文中像 module_eval 一样进行评估。
fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"
如果您想将其视为常规模块,请将该模块分配给一个常量(名称以大写字母开头)。
源代码
static VALUE
rb_mod_s_used_modules(VALUE _)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE ary = rb_ary_new();
while (cref) {
if (!NIL_P(CREF_REFINEMENTS(cref))) {
rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
}
cref = CREF_NEXT(cref);
}
return rb_funcall(ary, rb_intern("uniq"), 0);
}
返回当前作用域中使用的所有模块的数组。结果数组中模块的顺序未定义。
module A refine Object do end end module B refine Object do end end using A using B p Module.used_modules
产生
[B, A]
源代码
static VALUE
rb_mod_s_used_refinements(VALUE _)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE ary = rb_ary_new();
while (cref) {
if (!NIL_P(CREF_REFINEMENTS(cref))) {
rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary);
}
cref = CREF_NEXT(cref);
}
return ary;
}
返回当前作用域中使用的所有模块的数组。结果数组中模块的顺序未定义。
module A refine Object do end end module B refine Object do end end using A using B p Module.used_refinements
产生
[#<refinement:Object@B>, #<refinement:Object@A>]
公共实例方法
源代码
static VALUE
rb_mod_lt(VALUE mod, VALUE arg)
{
if (mod == arg) return Qfalse;
return rb_class_inherited_p(mod, arg);
}
如果 mod 是 other 的子类,则返回 true。如果 mod 与 other 相同或 mod 是 other 的祖先,则返回 false。如果两者之间没有关系,则返回 nil。(从类定义的角度考虑这种关系:“class A < B”意味着“A < B”。)
源代码
VALUE
rb_class_inherited_p(VALUE mod, VALUE arg)
{
if (mod == arg) return Qtrue;
if (RB_TYPE_P(arg, T_CLASS) && RB_TYPE_P(mod, T_CLASS)) {
// comparison between classes
size_t mod_depth = RCLASS_SUPERCLASS_DEPTH(mod);
size_t arg_depth = RCLASS_SUPERCLASS_DEPTH(arg);
if (arg_depth < mod_depth) {
// check if mod < arg
return RCLASS_SUPERCLASSES(mod)[arg_depth] == arg ?
Qtrue :
Qnil;
}
else if (arg_depth > mod_depth) {
// check if mod > arg
return RCLASS_SUPERCLASSES(arg)[mod_depth] == mod ?
Qfalse :
Qnil;
}
else {
// Depths match, and we know they aren't equal: no relation
return Qnil;
}
}
else {
if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
rb_raise(rb_eTypeError, "compared with non class/module");
}
if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
return Qtrue;
}
/* not mod < arg; check if mod > arg */
if (class_search_ancestor(arg, mod)) {
return Qfalse;
}
return Qnil;
}
}
如果 mod 是 other 的子类或与 other 相同,则返回 true。如果两者之间没有关系,则返回 nil。(从类定义的角度考虑这种关系:“class A < B”意味着“A < B”。)
源代码
static VALUE
rb_mod_cmp(VALUE mod, VALUE arg)
{
VALUE cmp;
if (mod == arg) return INT2FIX(0);
if (!CLASS_OR_MODULE_P(arg)) {
return Qnil;
}
cmp = rb_class_inherited_p(mod, arg);
if (NIL_P(cmp)) return Qnil;
if (cmp) {
return INT2FIX(-1);
}
return INT2FIX(1);
}
比较—根据 module 是否包含 other_module,它们是否相同,或者 module 是否被 other_module 包含,返回 -1、0、+1 或 nil。
如果 module 与 other_module 没有关系,如果 other_module 不是模块,或者如果这两个值无法比较,则返回 nil。
源代码
VALUE
rb_obj_equal(VALUE obj1, VALUE obj2)
{
return RBOOL(obj1 == obj2);
}
相等性—在 Object 级别,只有当 obj 和 other 是同一个对象时,== 才返回 true。通常,此方法会在后代类中被覆盖,以提供特定于类的含义。
与 == 不同,equal? 方法不应被子类覆盖,因为它用于确定对象标识(即,当且仅当 a 与 b 是同一对象时,a.equal?(b))。
obj = "a" other = obj.dup obj == other #=> true obj.equal? other #=> false obj.equal? obj #=> true
如果 obj 和 other 指的是同一个哈希键,则 eql? 方法返回 true。这被 Hash 用于测试成员的相等性。对于任何一对 eql? 返回 true 的对象,两个对象的 hash 值必须相等。因此,任何覆盖 eql? 的子类也应适当覆盖 hash。
对于 Object 类的对象,eql? 与 == 同义。子类通常通过将 eql? 别名为其覆盖的 == 方法来延续此传统,但也有例外。例如,Numeric 类型在 == 中执行类型转换,而不是在 eql? 中执行,所以
1 == 1.0 #=> true 1.eql? 1.0 #=> false
源代码
static VALUE
rb_mod_eqq(VALUE mod, VALUE arg)
{
return rb_obj_is_kind_of(arg, mod);
}
案例相等—如果 obj 是 mod 的实例或 mod 的后代的实例,则返回 true。对于模块的用途有限,但可以在 case 语句中使用,以按类对对象进行分类。
源代码
static VALUE
rb_mod_gt(VALUE mod, VALUE arg)
{
if (mod == arg) return Qfalse;
return rb_mod_ge(mod, arg);
}
如果 mod 是 other 的祖先,则返回 true。如果 mod 与 other 相同或 mod 是 other 的后代,则返回 false。如果两者之间没有关系,则返回 nil。(从类定义的角度考虑这种关系:“class A < B”意味着“B > A”。)
源代码
static VALUE
rb_mod_ge(VALUE mod, VALUE arg)
{
if (!CLASS_OR_MODULE_P(arg)) {
rb_raise(rb_eTypeError, "compared with non class/module");
}
return rb_class_inherited_p(arg, mod);
}
如果 mod 是 other 的祖先,或者这两个模块相同,则返回 true。如果两者之间没有关系,则返回 nil。(从类定义的角度考虑这种关系:“class A < B”意味着“B > A”。)
源代码
static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
ID oldid = rb_check_id(&oldname);
if (!oldid) {
rb_print_undef_str(mod, oldname);
}
VALUE id = rb_to_id(newname);
rb_alias(mod, id, oldid);
return ID2SYM(id);
}
使 new_name 成为方法 old_name 的新副本。这可以用于保留对被覆盖的方法的访问权限。
module Mod alias_method :orig_exit, :exit #=> :orig_exit def exit(code=0) puts "Exiting with code #{code}" orig_exit(code) end end include Mod exit(99)
产生
Exiting with code 99
源代码
VALUE
rb_mod_ancestors(VALUE mod)
{
VALUE p, ary = rb_ary_new();
VALUE refined_class = Qnil;
if (BUILTIN_TYPE(mod) == T_MODULE && FL_TEST(mod, RMODULE_IS_REFINEMENT)) {
refined_class = rb_refinement_module_get_refined_class(mod);
}
for (p = mod; p; p = RCLASS_SUPER(p)) {
if (p == refined_class) break;
if (p != RCLASS_ORIGIN(p)) continue;
if (BUILTIN_TYPE(p) == T_ICLASS) {
rb_ary_push(ary, METACLASS_OF(p));
}
else {
rb_ary_push(ary, p);
}
}
return ary;
}
返回在 mod 中包含/前置的模块列表(包括 mod 本身)。
module Mod include Math include Comparable prepend Enumerable end Mod.ancestors #=> [Enumerable, Mod, Comparable, Math] Math.ancestors #=> [Math] Enumerable.ancestors #=> [Enumerable]
源代码
VALUE
rb_mod_attr(int argc, VALUE *argv, VALUE klass)
{
if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
ID id = id_for_attr(klass, argv[0]);
VALUE names = rb_ary_new();
rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
rb_ary_push(names, ID2SYM(id));
if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
return names;
}
return rb_mod_attr_reader(argc, argv, klass);
}
第一种形式等同于 attr_reader。第二种形式等同于 attr_accessor(name),但已弃用。最后一种形式等同于 attr_reader(name),但已弃用。返回定义的 方法名称数组,类型为符号。
源代码
static VALUE
rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc * 2);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, TRUE, TRUE, TRUE);
rb_ary_push(names, ID2SYM(id));
rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
}
return names;
}
为此模块定义一个命名属性,其中名称为 symbol.id2name,创建一个实例变量 (@name) 和一个相应的访问方法来读取它。还会创建一个名为 name= 的方法来设置该属性。String 参数会转换为符号。返回定义的 方法名称数组,类型为符号。
module Mod attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=] end Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
源代码
static VALUE
rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, TRUE, FALSE, TRUE);
rb_ary_push(names, ID2SYM(id));
}
return names;
}
创建实例变量和相应的方法,这些方法返回每个实例变量的值。等同于依次对每个名称调用“attr:name”。 String 参数会转换为符号。返回定义的 方法名称数组,类型为符号。
源代码
static VALUE
rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, FALSE, TRUE, TRUE);
rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
}
return names;
}
创建一个访问器方法以允许分配给属性 symbol.id2name。String 参数会转换为符号。返回定义的 方法名称数组,类型为符号。
源代码
static VALUE
rb_mod_autoload(VALUE mod, VALUE sym, VALUE file)
{
ID id = rb_to_id(sym);
FilePathValue(file);
rb_autoload_str(mod, id, file);
return Qnil;
}
注册 filename,以便在 mod 的命名空间中首次访问 const(它可以是 String 或符号)时加载(使用 Kernel::require)。
module A end A.autoload(:B, "b") A::B.doit # autoloads "b"
如果 mod 中的 const 被定义为自动加载,则要加载的文件名将被替换为 filename。如果 const 被定义但不是作为自动加载,则不执行任何操作。
源代码
static VALUE
rb_mod_autoload_p(int argc, VALUE *argv, VALUE mod)
{
int recur = (rb_check_arity(argc, 1, 2) == 1) ? TRUE : RTEST(argv[1]);
VALUE sym = argv[0];
ID id = rb_check_id(&sym);
if (!id) {
return Qnil;
}
return rb_autoload_at_p(mod, id, recur);
}
如果 name 在 mod 的命名空间或其祖先之一中注册为 autoload,则返回要加载的 filename。
module A end A.autoload(:B, "b") A.autoload?(:B) #=> "b"
如果 inherit 为 false,则查找仅检查接收器中的自动加载
class A autoload :CONST, "const.rb" end class B < A end B.autoload?(:CONST) #=> "const.rb", found in A (ancestor) B.autoload?(:CONST, false) #=> nil, not found in B itself
在 mod 的上下文中评估字符串或代码块,但当给定一个代码块时,常量/类变量查找不受影响。这可以用于向类添加方法。module_eval 返回评估其参数的结果。可选的 filename 和 lineno 参数设置错误消息的文本。
class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)
产生
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
在类/模块的上下文中评估给定的代码块。代码块中定义的方法将属于接收器。传递给该方法的任何参数都将传递给代码块。如果代码块需要访问实例变量,则可以使用此方法。
class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()
产生
Hello there!
源代码
static VALUE
rb_mod_cvar_defined(VALUE obj, VALUE iv)
{
ID id = id_for_var(obj, iv, class);
if (!id) {
return Qfalse;
}
return rb_cvar_defined(obj, id);
}
如果给定的类变量在 obj 中定义,则返回 true。String 参数会转换为符号。
class Fred @@foo = 99 end Fred.class_variable_defined?(:@@foo) #=> true Fred.class_variable_defined?(:@@bar) #=> false
源代码
static VALUE
rb_mod_cvar_get(VALUE obj, VALUE iv)
{
ID id = id_for_var(obj, iv, class);
if (!id) {
rb_name_err_raise("uninitialized class variable %1$s in %2$s",
obj, iv);
}
return rb_cvar_get(obj, id);
}
返回给定类变量的值(或抛出一个 NameError 异常)。对于常规类变量,应包括变量名称的 @@ 部分。String 参数会转换为符号。
class Fred @@foo = 99 end Fred.class_variable_get(:@@foo) #=> 99
源代码
static VALUE
rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
{
ID id = id_for_var(obj, iv, class);
if (!id) id = rb_intern_str(iv);
rb_cvar_set(obj, id, val);
return val;
}
将名为符号的类变量设置为给定的对象。如果类变量名以字符串形式传递,则该字符串将转换为符号。
class Fred @@foo = 99 def foo @@foo end end Fred.class_variable_set(:@@foo, 101) #=> 101 Fred.new.foo #=> 101
源代码
VALUE
rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
{
bool inherit = true;
st_table *tbl;
if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
if (inherit) {
tbl = mod_cvar_of(mod, 0);
}
else {
tbl = mod_cvar_at(mod, 0);
}
return cvar_list(tbl);
}
返回 mod 中类变量名称的数组。 这包括任何包含的模块中的类变量名称,除非 inherit 参数设置为 false。
class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> [:@@var1] Two.class_variables #=> [:@@var2, :@@var1] Two.class_variables(false) #=> [:@@var2]
源代码
static VALUE
rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return Qfalse;
return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else {
return Qfalse;
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
#if 0
mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
if (UNDEF_P(mod)) return Qfalse;
#else
if (!RTEST(recur)) {
if (!rb_const_defined_at(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get_at(mod, id);
}
else if (beglen == 0) {
if (!rb_const_defined(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get(mod, id);
}
else {
if (!rb_const_defined_from(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get_from(mod, id);
}
#endif
if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
}
return Qtrue;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
说明 mod 或其祖先是否具有给定名称的常量。
Float.const_defined?(:EPSILON) #=> true, found in Float itself Float.const_defined?("String") #=> true, found in Object (ancestor) BasicObject.const_defined?(:Hash) #=> false
如果 mod 是一个 Module,则还会检查 Object 及其祖先。
Math.const_defined?(:String) #=> true, found in Object
在每个检查的类或模块中,如果常量不存在但存在该常量的自动加载,则直接返回 true,而不进行自动加载。
module Admin autoload :User, 'admin/user' end Admin.const_defined?(:User) #=> true
如果找不到常量,则不会调用回调 const_missing,并且该方法返回 false。
如果 inherit 为 false,则查找仅检查接收者中的常量。
IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor) IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
在这种情况下,相同的自动加载逻辑适用。
如果参数不是有效的常量名称,则会引发 NameError 错误,消息为 “错误的常量名称名称”。
Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
源代码
static VALUE
rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return rb_const_missing(mod, name);
return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
part = rb_str_intern(part);
mod = rb_const_missing(mod, part);
continue;
}
else {
rb_mod_const_missing(mod, part);
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
#if 0
mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
#else
if (!RTEST(recur)) {
mod = rb_const_get_at(mod, id);
}
else if (beglen == 0) {
mod = rb_const_get(mod, id);
}
else {
mod = rb_const_get_from(mod, id);
}
#endif
}
return mod;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
检查 mod 中是否具有给定名称的常量。如果设置了 inherit,则查找还将搜索祖先(如果 mod 是一个 Module,则还会搜索 Object)。
如果找到了定义,则返回常量的值,否则会引发 NameError 错误。
Math.const_get(:PI) #=> 3.14159265358979
如果提供了命名空间的类名称,则此方法将递归查找常量名称。例如
module Foo; class Bar; end end Object.const_get 'Foo::Bar'
在每次查找时都将遵守 inherit 标志。例如
module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError
如果参数不是有效的常量名称,则会引发 NameError 错误,并显示警告 “错误的常量名称”。
Object.const_get 'foobar' #=> NameError: wrong constant name foobar
源代码
VALUE
rb_mod_const_missing(VALUE klass, VALUE name)
{
rb_execution_context_t *ec = GET_EC();
VALUE ref = ec->private_const_reference;
rb_vm_pop_cfunc_frame();
if (ref) {
ec->private_const_reference = 0;
rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name);
}
uninitialized_constant(klass, name);
UNREACHABLE_RETURN(Qnil);
}
当引用 mod 中未定义的常量时调用。它会传递一个未定义常量的符号,并返回用于该常量的值。例如,考虑
def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
如上面的示例所示,const_missing 不需要在 mod 中创建缺失的常量,尽管这通常是一种副作用。调用者在触发时获取其返回值。如果常量也被定义,则进一步的查找将不会触发 const_missing,并像往常一样返回存储在常量中的值。否则,将再次调用 const_missing。
在下一个示例中,当引用未定义的常量时,const_missing 尝试加载一个文件,该文件的路径是常量名称的小写版本(因此,假设类 Fred 位于文件 fred.rb 中)。如果定义为加载该文件的副作用,则该方法返回存储在常量中的值。这实现了类似于 Kernel#autoload 和 Module#autoload 的自动加载功能,尽管它在重要方面有所不同。
def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Constant not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file const_get(name, false) end
源代码
static VALUE
rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
{
ID id = id_for_var(mod, name, const);
if (!id) id = rb_intern_str(name);
rb_const_set(mod, id, value);
return value;
}
将指定的常量设置为给定的对象,并返回该对象。如果先前不存在具有给定名称的常量,则创建一个新的常量。
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
如果 sym 或 str 不是有效的常量名称,则会引发 NameError 错误,并显示警告 “错误的常量名称”。
Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
源代码
static VALUE
rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur, loc = Qnil;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return Qnil;
return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else {
return Qnil;
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
if (p < pend) {
if (RTEST(recur)) {
mod = rb_const_get(mod, id);
}
else {
mod = rb_const_get_at(mod, id);
}
if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
}
else {
if (RTEST(recur)) {
loc = rb_const_source_location(mod, id);
}
else {
loc = rb_const_source_location_at(mod, id);
}
break;
}
recur = Qfalse;
}
return loc;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
返回包含指定常量定义的 Ruby 源文件名和行号。如果找不到指定的常量,则返回 nil。如果找到常量,但无法提取其源位置(常量在 C 代码中定义),则返回空数组。
inherit 指定是否在 mod.ancestors 中查找(默认为 true)。
# test.rb: class A # line 1 C1 = 1 C2 = 2 end module M # line 6 C3 = 3 end class B < A # line 10 include M C4 = 4 end class A # continuation of A definition C2 = 8 # constant redefinition; warned yet allowed end p B.const_source_location('C4') # => ["test.rb", 12] p B.const_source_location('C3') # => ["test.rb", 7] p B.const_source_location('C1') # => ["test.rb", 2] p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported p Object.const_source_location('String') # => [] -- constant is defined in C code
源代码
VALUE
rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
{
bool inherit = true;
if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
if (inherit) {
return rb_const_list(rb_mod_const_of(mod, 0));
}
else {
return rb_local_constants(mod);
}
}
返回 mod 中可访问的常量名称的数组。这包括任何包含的模块中的常量名称(本节开头的示例),除非 inherit 参数设置为 false。
该实现不保证常量的生成顺序。
IO.constants.include?(:SYNC) #=> true IO.constants(false).include?(:SYNC) #=> false
另请参阅 Module#const_defined?。
源代码
static VALUE
rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
{
const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
const rb_scope_visibility_t *scope_visi = &default_scope_visi;
if (cref) {
scope_visi = CREF_SCOPE_VISI(cref);
}
return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
}
在接收者中定义一个实例方法。method 参数可以是 Proc、Method 或 UnboundMethod 对象。如果指定了一个块,则该块用作方法体。如果块或 method 参数具有参数,则它们将用作方法参数。此块使用 instance_eval 进行求值。
class A def fred puts "In Fred" end def create_method(name, &block) self.class.define_method(name, &block) end define_method(:wilma) { puts "Charge it!" } define_method(:flint) {|name| puts "I'm #{name}!"} end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.flint('Dino') a.create_method(:betty) { p self } a.betty
产生
In Fred Charge it! I'm Dino! #<B:0x401b39e8>
源代码
VALUE
rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
return obj;
}
使现有常量列表被弃用。尝试引用它们将产生警告。
module HTTP NotFound = Exception.new NOT_FOUND = NotFound # previous version of the library used this name deprecate_constant :NOT_FOUND end HTTP::NOT_FOUND # warning: constant HTTP::NOT_FOUND is deprecated
源代码
static VALUE
rb_mod_freeze(VALUE mod)
{
rb_class_name(mod);
return rb_obj_freeze(mod);
}
防止进一步修改 mod。
此方法返回 self。
源代码
static VALUE
rb_mod_include(int argc, VALUE *argv, VALUE module)
{
int i;
ID id_append_features, id_included;
CONST_ID(id_append_features, "append_features");
CONST_ID(id_included, "included");
if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Refinement#include has been removed");
}
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
for (i = 0; i < argc; i++) {
Check_Type(argv[i], T_MODULE);
if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Cannot include refinement");
}
}
while (argc--) {
rb_funcall(argv[argc], id_append_features, 1, module);
rb_funcall(argv[argc], id_included, 1, module);
}
return module;
}
按相反的顺序在每个参数上调用 Module.append_features。
源代码
VALUE
rb_mod_include_p(VALUE mod, VALUE mod2)
{
VALUE p;
Check_Type(mod2, T_MODULE);
for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
if (BUILTIN_TYPE(p) == T_ICLASS && !FL_TEST(p, RICLASS_IS_ORIGIN)) {
if (METACLASS_OF(p) == mod2) return Qtrue;
}
}
return Qfalse;
}
如果 module 包含在 mod 或 mod 的祖先中,或将其置于其之前,则返回 true。
module A end class B include A end class C < B end B.include?(A) #=> true C.include?(A) #=> true A.include?(A) #=> false
源代码
VALUE
rb_mod_included_modules(VALUE mod)
{
VALUE ary = rb_ary_new();
VALUE p;
VALUE origin = RCLASS_ORIGIN(mod);
for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) {
VALUE m = METACLASS_OF(p);
if (RB_TYPE_P(m, T_MODULE))
rb_ary_push(ary, m);
}
}
return ary;
}
返回包含或置于 mod 或 mod 的祖先中的模块列表。
module Sub end module Mixin prepend Sub end module Outer include Mixin end Mixin.included_modules #=> [Sub] Outer.included_modules #=> [Sub, Mixin]
源代码
static VALUE
rb_mod_instance_method(VALUE mod, VALUE vid)
{
ID id = rb_check_id(&vid);
if (!id) {
rb_method_name_error(mod, vid);
}
return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
}
返回一个 UnboundMethod,表示 mod 中给定的实例方法。
class Interpreter def do_a() print "there, "; end def do_d() print "Hello "; end def do_e() print "!\n"; end def do_v() print "Dave"; end Dispatcher = { "a" => instance_method(:do_a), "d" => instance_method(:do_d), "e" => instance_method(:do_e), "v" => instance_method(:do_v) } def interpret(string) string.each_char {|b| Dispatcher[b].bind(self).call } end end interpreter = Interpreter.new interpreter.interpret('dave')
产生
Hello there, Dave!
源代码
VALUE
rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
}
返回一个数组,其中包含接收者中的公共和受保护的实例方法的名称。对于模块,这些是公共和受保护的方法;对于类,它们是实例方法(而不是单例方法)。如果可选参数为 false,则不包括任何祖先的方法。
module A def method1() end end class B include A def method2() end end class C < B def method3() end end A.instance_methods(false) #=> [:method1] B.instance_methods(false) #=> [:method2] B.instance_methods(true).include?(:method1) #=> true C.instance_methods(false) #=> [:method3] C.instance_methods.include?(:method2) #=> true
请注意,当前类中的方法可见性更改以及别名,均被此方法视为当前类的方法。
class C < B alias method4 method2 protected :method2 end C.instance_methods(false).sort #=> [:method2, :method3, :method4]
源代码
static VALUE
rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
{
rb_method_visibility_t visi = check_definition_visibility(mod, argc, argv);
return RBOOL(visi == METHOD_VISI_PUBLIC || visi == METHOD_VISI_PROTECTED);
}
如果 mod 定义了指定的方法,则返回 true。如果设置了 inherit,则查找还将搜索 mod 的祖先。将匹配公共方法和受保护的方法。String 参数将转换为符号。
module A def method1() end def protected_method1() end protected :protected_method1 end class B def method2() end def private_method2() end private :private_method2 end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method2", true #=> true C.method_defined? "method2", false #=> false C.method_defined? "method3" #=> true C.method_defined? "protected_method1" #=> true C.method_defined? "method4" #=> false C.method_defined? "private_method2" #=> false
源代码
static VALUE
rb_mod_module_eval_internal(int argc, const VALUE *argv, VALUE mod)
{
return specific_eval(argc, argv, mod, FALSE, RB_PASS_CALLED_KEYWORDS);
}
在 mod 的上下文中评估字符串或代码块,但当给定一个代码块时,常量/类变量查找不受影响。这可以用于向类添加方法。module_eval 返回评估其参数的结果。可选的 filename 和 lineno 参数设置错误消息的文本。
class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)
产生
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
源代码
static VALUE
rb_mod_module_exec_internal(int argc, const VALUE *argv, VALUE mod)
{
return yield_under(mod, FALSE, argc, argv, RB_PASS_CALLED_KEYWORDS);
}
在类/模块的上下文中评估给定的代码块。代码块中定义的方法将属于接收器。传递给该方法的任何参数都将传递给代码块。如果代码块需要访问实例变量,则可以使用此方法。
class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()
产生
Hello there!
源代码
VALUE
rb_mod_name(VALUE mod)
{
// YJIT needs this function to not allocate.
bool permanent;
return classname(mod, &permanent);
}
返回模块 mod 的名称。对于匿名模块,返回 nil。
源代码
static VALUE
rb_mod_prepend(int argc, VALUE *argv, VALUE module)
{
int i;
ID id_prepend_features, id_prepended;
if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Refinement#prepend has been removed");
}
CONST_ID(id_prepend_features, "prepend_features");
CONST_ID(id_prepended, "prepended");
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
for (i = 0; i < argc; i++) {
Check_Type(argv[i], T_MODULE);
if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Cannot prepend refinement");
}
}
while (argc--) {
rb_funcall(argv[argc], id_prepend_features, 1, module);
rb_funcall(argv[argc], id_prepended, 1, module);
}
return module;
}
按相反的顺序在每个参数上调用 Module.prepend_features。
源代码
static VALUE
rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
{
set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PRIVATE);
return obj;
}
使现有的类方法成为私有方法。通常用于隐藏默认的构造函数 new。
String 参数将转换为符号。也接受符号和/或字符串的 Array。
class SimpleSingleton # Not thread safe private_class_method :new def SimpleSingleton.create(*args, &block) @me = new(*args, &block) if ! @me @me end end
源代码
VALUE
rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
return obj;
}
使现有常量列表成为私有常量。
源代码
VALUE
rb_class_private_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
}
返回在 mod 中定义的私有实例方法列表。如果可选参数为 false,则不包括任何祖先的方法。
module Mod def method1() end private :method1 def method2() end end Mod.instance_methods #=> [:method2] Mod.private_instance_methods #=> [:method1]
源代码
static VALUE
rb_mod_private_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PRIVATE);
}
如果 mod 定义了指定的私有方法,则返回 true。如果设置了 inherit,则查找还将搜索 mod 的祖先。String 参数将转换为符号。
module A def method1() end end class B private def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.private_method_defined? "method1" #=> false C.private_method_defined? "method2" #=> true C.private_method_defined? "method2", true #=> true C.private_method_defined? "method2", false #=> false C.method_defined? "method2" #=> false
源代码
VALUE
rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
}
返回在 mod 中定义的受保护实例方法列表。如果可选参数为 false,则不包括任何祖先的方法。
源代码
static VALUE
rb_mod_protected_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PROTECTED);
}
如果 mod 定义了指定的受保护方法,则返回 true。如果设置了 inherit,则查找还将搜索 mod 的祖先。String 参数将转换为符号。
module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.protected_method_defined? "method1" #=> false C.protected_method_defined? "method2" #=> true C.protected_method_defined? "method2", true #=> true C.protected_method_defined? "method2", false #=> false C.method_defined? "method2" #=> true
源代码
源代码
VALUE
rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
return obj;
}
使现有常量列表成为公共常量。
源代码
static VALUE
rb_mod_public_instance_method(VALUE mod, VALUE vid)
{
ID id = rb_check_id(&vid);
if (!id) {
rb_method_name_error(mod, vid);
}
return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
}
类似于 instance_method,仅搜索公共方法。
源代码
VALUE
rb_class_public_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
}
返回在 mod 中定义的公共实例方法列表。如果可选参数为 false,则不包括任何祖先的方法。
源代码
static VALUE
rb_mod_public_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PUBLIC);
}
如果 mod 定义了指定的公共方法,则返回 true。如果设置了 inherit,则查找还将搜索 mod 的祖先。String 参数将转换为符号。
module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.public_method_defined? "method1" #=> true C.public_method_defined? "method1", true #=> true C.public_method_defined? "method1", false #=> true C.public_method_defined? "method2" #=> false C.method_defined? "method2" #=> true
源代码
static VALUE
mod_refinements(VALUE self)
{
ID id_refinements;
VALUE refinements;
CONST_ID(id_refinements, "__refinements__");
refinements = rb_attr_get(self, id_refinements);
if (NIL_P(refinements)) {
return rb_ary_new();
}
return rb_hash_values(refinements);
}
返回接收者中定义的 Refinement 数组。
module A refine Integer do end refine String do end end p A.refinements
产生
[#<refinement:Integer@A>, #<refinement:String@A>]
源代码
VALUE
rb_mod_remove_cvar(VALUE mod, VALUE name)
{
const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
st_data_t val;
if (!id) {
goto not_defined;
}
rb_check_frozen(mod);
val = rb_ivar_delete(mod, id, Qundef);
if (!UNDEF_P(val)) {
return (VALUE)val;
}
if (rb_cvar_defined(mod, id)) {
rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
}
not_defined:
rb_name_err_raise("class variable %1$s not defined for %2$s",
mod, name);
UNREACHABLE_RETURN(Qundef);
}
从接收者中移除指定的类变量,并返回该变量的值。
class Example @@var = 99 puts remove_class_variable(:@@var) p(defined? @@var) end
产生
99 nil
源代码
static VALUE
rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_name_err_raise("method '%1$s' not defined in %2$s",
mod, v);
}
remove_method(mod, id);
}
return mod;
}
从当前类中移除由 symbol 标识的方法。有关示例,请参阅 Module#undef_method。String 参数将转换为符号。
源代码
VALUE
rb_mod_set_temporary_name(VALUE mod, VALUE name)
{
// We don't allow setting the name if the classpath is already permanent:
if (RCLASS_EXT(mod)->permanent_classpath) {
rb_raise(rb_eRuntimeError, "can't change permanent name");
}
if (NIL_P(name)) {
// Set the temporary classpath to NULL (anonymous):
RCLASS_SET_CLASSPATH(mod, 0, FALSE);
}
else {
// Ensure the name is a string:
StringValue(name);
if (RSTRING_LEN(name) == 0) {
rb_raise(rb_eArgError, "empty class/module name");
}
if (is_constant_path(name)) {
rb_raise(rb_eArgError, "the temporary name must not be a constant path to avoid confusion");
}
// Set the temporary classpath to the given name:
RCLASS_SET_CLASSPATH(mod, name, FALSE);
}
return mod;
}
设置模块的临时名称。此名称反映在模块的内省以及与其相关的值中,例如实例、常量和方法。
该名称应为 nil 或不是有效常量路径的非空字符串(以避免混淆永久名称和临时名称)。
该方法可用于区分动态生成的类和模块,而无需将它们分配给常量。
如果通过将其分配给常量来为模块提供永久名称,则将丢弃临时名称。不能将临时名称分配给具有永久名称的模块。
如果给定的名称为 nil,则该模块将再次变为匿名。
示例
m = Module.new # => #<Module:0x0000000102c68f38> m.name #=> nil m.set_temporary_name("fake_name") # => fake_name m.name #=> "fake_name" m.set_temporary_name(nil) # => #<Module:0x0000000102c68f38> m.name #=> nil c = Class.new c.set_temporary_name("MyClass(with description)") c.new # => #<MyClass(with description):0x0....> c::M = m c::M.name #=> "MyClass(with description)::M" # Assigning to a constant replaces the name with a permanent one C = c C.name #=> "C" C::M.name #=> "C::M" c.new # => #<C:0x0....>
源代码
static VALUE
rb_mod_singleton_p(VALUE klass)
{
return RBOOL(RCLASS_SINGLETON_P(klass));
}
如果 mod 是单例类,则返回 true;如果它是普通类或模块,则返回 false。
class C end C.singleton_class? #=> false C.singleton_class.singleton_class? #=> true
源代码
VALUE
rb_mod_to_s(VALUE klass)
{
ID id_defined_at;
VALUE refined_class, defined_at;
if (RCLASS_SINGLETON_P(klass)) {
VALUE s = rb_usascii_str_new2("#<Class:");
VALUE v = RCLASS_ATTACHED_OBJECT(klass);
if (CLASS_OR_MODULE_P(v)) {
rb_str_append(s, rb_inspect(v));
}
else {
rb_str_append(s, rb_any_to_s(v));
}
rb_str_cat2(s, ">");
return s;
}
refined_class = rb_refinement_module_get_refined_class(klass);
if (!NIL_P(refined_class)) {
VALUE s = rb_usascii_str_new2("#<refinement:");
rb_str_concat(s, rb_inspect(refined_class));
rb_str_cat2(s, "@");
CONST_ID(id_defined_at, "__defined_at__");
defined_at = rb_attr_get(klass, id_defined_at);
rb_str_concat(s, rb_inspect(defined_at));
rb_str_cat2(s, ">");
return s;
}
return rb_class_name(klass);
}
返回表示此模块或类的字符串。对于基本类和模块,这是名称。对于单例,我们还显示有关我们附加到的事物的信息。
源代码
static VALUE
rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_method_name_error(mod, v);
}
rb_undef(mod, id);
}
return mod;
}
阻止当前类响应对指定方法的调用。将其与 remove_method 进行对比,后者会从特定类中删除该方法;Ruby 仍将搜索超类和混合的模块以查找可能的接收者。String 参数将转换为符号。
class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello
产生
In child In parent prog.rb:23: undefined method 'hello' for #<Child:0x401b3bb4> (NoMethodError)
源代码
VALUE
rb_class_undefined_instance_methods(VALUE mod)
{
VALUE include_super = Qfalse;
return class_instance_method_list(1, &include_super, mod, 0, ins_methods_undef_i);
}
返回在 mod 中定义的未定义实例方法列表。不包含任何祖先的未定义方法。
私有实例方法
源代码
static VALUE
rb_mod_append_features(VALUE module, VALUE include)
{
if (!CLASS_OR_MODULE_P(include)) {
Check_Type(include, T_CLASS);
}
rb_include_module(include, module);
return module;
}
当此模块被包含在另一个模块中时,Ruby 会调用此模块中的 append_features,并将接收模块传递给 mod。Ruby 的默认实现是将此模块的常量、方法和模块变量添加到 mod 中,前提是此模块尚未添加到 mod 或其祖先之一。另请参阅 Module#include。
源代码
#define rb_obj_mod_const_added rb_obj_dummy1
每当在接收者上分配常量时作为回调调用
module Chatty def self.const_added(const_name) super puts "Added #{const_name.inspect}" end FOO = 1 end
产生
Added :FOO
源代码
static VALUE
rb_mod_extend_object(VALUE mod, VALUE obj)
{
rb_extend_object(obj, mod);
return obj;
}
通过添加此模块的常量和方法(作为单例方法添加)来扩展指定的对象。这是 Object#extend 使用的回调方法。
module Picky def Picky.extend_object(o) if String === o puts "Can't add Picky to a String" else puts "Picky added to #{o.class}" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky
产生
Picky added to Array Can't add Picky to a String
源代码
#define rb_obj_mod_extended rb_obj_dummy1
等同于 included,但用于扩展的模块。
module A def self.extended(mod) puts "#{self} extended in #{mod}" end end module Enumerable extend A end # => prints "A extended in Enumerable"
源代码
#define rb_obj_mod_included rb_obj_dummy1
每当接收者被包含在另一个模块或类中时调用的回调。如果您的代码希望在模块被包含在另一个模块中时执行某些操作,则应优先使用此方法,而不是 Module.append_features。
module A def A.included(mod) puts "#{self} included in #{mod}" end end module Enumerable include A end # => prints "A included in Enumerable"
源代码
#define rb_obj_mod_method_added rb_obj_dummy1
每当实例方法被添加到接收者时作为回调调用。
module Chatty def self.method_added(method_name) puts "Adding #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end end
产生
Adding :some_instance_method
源代码
#define rb_obj_mod_method_removed rb_obj_dummy1
每当从接收者中删除实例方法时作为回调调用。
module Chatty def self.method_removed(method_name) puts "Removing #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end class << self remove_method :some_class_method end remove_method :some_instance_method end
产生
Removing :some_instance_method
源代码
#define rb_obj_mod_method_undefined rb_obj_dummy1
每当从接收者中取消定义实例方法时作为回调调用。
module Chatty def self.method_undefined(method_name) puts "Undefining #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end class << self undef_method :some_class_method end undef_method :some_instance_method end
产生
Undefining :some_instance_method
源代码
static VALUE
rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
{
int i;
ID id;
const rb_method_entry_t *me;
if (!RB_TYPE_P(module, T_MODULE)) {
rb_raise(rb_eTypeError, "module_function must be called for modules");
}
if (argc == 0) {
rb_scope_module_func_set();
return Qnil;
}
set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE);
for (i = 0; i < argc; i++) {
VALUE m = module;
id = rb_to_id(argv[i]);
for (;;) {
me = search_method(m, id, 0);
if (me == 0) {
me = search_method(rb_cObject, id, 0);
}
if (UNDEFINED_METHOD_ENTRY_P(me)) {
rb_print_undef(module, id, METHOD_VISI_UNDEF);
}
if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
break; /* normal case: need not to follow 'super' link */
}
m = RCLASS_SUPER(m);
if (!m)
break;
}
rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC);
}
if (argc == 1) {
return argv[0];
}
return rb_ary_new_from_values(argc, argv);
}
为命名方法创建模块函数。这些函数可以使用模块作为接收者调用,并且也可作为混合到模块中的类的实例方法使用。Module 函数是原始函数的副本,因此可以独立更改。实例方法版本被设为私有。如果使用时没有参数,则随后定义的方法将成为模块函数。String 参数将转换为符号。如果传递单个参数,则返回该参数。如果没有传递参数,则返回 nil。如果传递多个参数,则参数将作为数组返回。
module Mod def one "This is one" end module_function :one end class Cls include Mod def call_one one end end Mod.one #=> "This is one" c = Cls.new c.call_one #=> "This is one" module Mod def one "This is the new one" end end Mod.one #=> "This is one" c.call_one #=> "This is the new one"
源代码
static VALUE
rb_mod_prepend_features(VALUE module, VALUE prepend)
{
if (!CLASS_OR_MODULE_P(prepend)) {
Check_Type(prepend, T_CLASS);
}
rb_prepend_module(prepend, module);
return module;
}
当此模块被前置到另一个模块中时,Ruby 会调用此模块中的 prepend_features,并将接收模块传递给 mod。Ruby 的默认实现是将此模块的常量、方法和模块变量覆盖到 mod 上,前提是此模块尚未添加到 mod 或其祖先之一。另请参阅 Module#prepend。
源代码
#define rb_obj_mod_prepended rb_obj_dummy1
等同于 included,但用于前置的模块。
module A def self.prepended(mod) puts "#{self} prepended to #{mod}" end end module Enumerable prepend A end # => prints "A prepended to Enumerable"
源代码
static VALUE
rb_mod_private(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE);
}
如果没有参数,则将随后定义的方法的默认可见性设置为私有。如果有参数,则将命名方法设置为具有私有可见性。String 参数将转换为符号。也接受符号和/或字符串的 Array。如果传递单个参数,则返回该参数。如果没有传递参数,则返回 nil。如果传递多个参数,则参数将作为数组返回。
module Mod def a() end def b() end private def c() end private :a end Mod.private_instance_methods #=> [:a, :c]
请注意,要在 RDoc 上显示私有方法,请使用 :doc:。
源代码
static VALUE
rb_mod_protected(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
}
如果没有参数,则将随后定义的方法的默认可见性设置为受保护。如果有参数,则将命名方法设置为具有受保护的可见性。String 参数将转换为符号。也接受符号和/或字符串的 Array。如果传递单个参数,则返回该参数。如果没有传递参数,则返回 nil。如果传递多个参数,则参数将作为数组返回。
如果方法具有受保护的可见性,则仅在上下文的 self 与方法相同时才可调用(方法定义或 instance_eval)。此行为与 Java 的受保护方法不同。通常应使用 private。
请注意,受保护的方法速度较慢,因为它无法使用内联缓存。
要在 RDoc 上显示私有方法,请使用 :doc: 而不是此方法。
源代码
源代码
static VALUE
rb_mod_refine(VALUE module, VALUE klass)
{
VALUE refinement;
ID id_refinements, id_activated_refinements,
id_refined_class, id_defined_at;
VALUE refinements, activated_refinements;
rb_thread_t *th = GET_THREAD();
VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
if (block_handler == VM_BLOCK_HANDLER_NONE) {
rb_raise(rb_eArgError, "no block given");
}
if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
}
ensure_class_or_module(klass);
CONST_ID(id_refinements, "__refinements__");
refinements = rb_attr_get(module, id_refinements);
if (NIL_P(refinements)) {
refinements = hidden_identity_hash_new();
rb_ivar_set(module, id_refinements, refinements);
}
CONST_ID(id_activated_refinements, "__activated_refinements__");
activated_refinements = rb_attr_get(module, id_activated_refinements);
if (NIL_P(activated_refinements)) {
activated_refinements = hidden_identity_hash_new();
rb_ivar_set(module, id_activated_refinements,
activated_refinements);
}
refinement = rb_hash_lookup(refinements, klass);
if (NIL_P(refinement)) {
VALUE superclass = refinement_superclass(klass);
refinement = rb_refinement_new();
RCLASS_SET_SUPER(refinement, superclass);
RUBY_ASSERT(BUILTIN_TYPE(refinement) == T_MODULE);
FL_SET(refinement, RMODULE_IS_REFINEMENT);
CONST_ID(id_refined_class, "__refined_class__");
rb_ivar_set(refinement, id_refined_class, klass);
CONST_ID(id_defined_at, "__defined_at__");
rb_ivar_set(refinement, id_defined_at, module);
rb_hash_aset(refinements, klass, refinement);
add_activated_refinement(activated_refinements, klass, refinement);
}
rb_yield_refine_block(refinement, activated_refinements);
return refinement;
}
在接收者中精炼 mod。
返回定义了精炼方法的模块。
源代码
VALUE
rb_mod_remove_const(VALUE mod, VALUE name)
{
const ID id = id_for_var(mod, name, a, constant);
if (!id) {
undefined_constant(mod, name);
}
return rb_const_remove(mod, id);
}
删除给定常量的定义,返回该常量的先前值。如果该常量引用了一个模块,则这不会更改该模块的名称,并可能导致混淆。
源代码
static VALUE
rb_mod_ruby2_keywords(int argc, VALUE *argv, VALUE module)
{
int i;
VALUE origin_class = RCLASS_ORIGIN(module);
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
rb_check_frozen(module);
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID name = rb_check_id(&v);
rb_method_entry_t *me;
VALUE defined_class;
if (!name) {
rb_print_undef_str(module, v);
}
me = search_method(origin_class, name, &defined_class);
if (!me && RB_TYPE_P(module, T_MODULE)) {
me = search_method(rb_cObject, name, &defined_class);
}
if (UNDEFINED_METHOD_ENTRY_P(me) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_print_undef(module, name, METHOD_VISI_UNDEF);
}
if (module == defined_class || origin_class == defined_class) {
switch (me->def->type) {
case VM_METHOD_TYPE_ISEQ:
if (ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_rest &&
!ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kw &&
!ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kwrest) {
ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.ruby2_keywords = 1;
rb_clear_method_cache(module, name);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or method does not accept argument splat)", QUOTE_ID(name));
}
break;
case VM_METHOD_TYPE_BMETHOD: {
VALUE procval = me->def->body.bmethod.proc;
if (vm_block_handler_type(procval) == block_handler_type_proc) {
procval = vm_proc_to_block_handler(VM_BH_TO_PROC(procval));
}
if (vm_block_handler_type(procval) == block_handler_type_iseq) {
const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(procval);
const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
if (ISEQ_BODY(iseq)->param.flags.has_rest &&
!ISEQ_BODY(iseq)->param.flags.has_kw &&
!ISEQ_BODY(iseq)->param.flags.has_kwrest) {
ISEQ_BODY(iseq)->param.flags.ruby2_keywords = 1;
rb_clear_method_cache(module, name);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or method does not accept argument splat)", QUOTE_ID(name));
}
break;
}
}
/* fallthrough */
default:
rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method not defined in Ruby)", QUOTE_ID(name));
break;
}
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (can only set in method defining module)", QUOTE_ID(name));
}
}
return Qnil;
}
对于给定的方法名称,将该方法标记为通过普通参数 splat 传递关键字。这应该只在接受参数 splat (*args) 但不接受显式关键字或关键字 splat 的方法上调用。它标记方法,以便如果使用关键字参数调用该方法,则最终的哈希参数会被标记一个特殊标志,以便如果它是另一个方法调用的普通参数 splat 的最后一个元素,并且该方法调用不包含显式关键字或关键字 splat,则最后一个元素将被解释为关键字。换句话说,关键字将通过该方法传递给其他方法。
这应该只用于将关键字委托给其他方法的方法,并且仅用于与 3.0 之前的 Ruby 版本向后兼容。有关 ruby2_keywords 存在的原因以及何时以及如何使用它的详细信息,请参阅 www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/。
此方法可能会在某个时候被删除,因为它仅为了向后兼容而存在。由于它在 2.7 之前的 Ruby 版本中不存在,因此请在调用它之前检查模块是否响应此方法
module Mod def foo(meth, *args, &block) send(:"do_#{meth}", *args, &block) end ruby2_keywords(:foo) if respond_to?(:ruby2_keywords, true) end
但是,请注意,如果删除了 ruby2_keywords 方法,则使用上述方法的 foo 方法的行为将发生更改,以便该方法不会传递关键字。
源代码
static VALUE
mod_using(VALUE self, VALUE module)
{
rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
if (prev_frame_func()) {
rb_raise(rb_eRuntimeError,
"Module#using is not permitted in methods");
}
if (prev_cfp && prev_cfp->self != self) {
rb_raise(rb_eRuntimeError, "Module#using is not called on self");
}
if (rb_block_given_p()) {
ignored_block(module, "Module#");
}
rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
return self;
}
将 module 中的类精炼导入到当前的类或模块定义中。