模块 Warning
Warning
模块包含一个名为 warn
的方法,并且该模块扩展了自身,使得 Warning.warn
可用。对于 Ruby 发出的所有警告,都会调用 Warning.warn
。默认情况下,警告会打印到 $stderr。
更改 Warning.warn
的行为有助于自定义 Ruby 如何处理警告,例如,过滤某些警告,和/或将警告输出到 $stderr
之外的其他地方。
如果你想更改 Warning.warn
的行为,你应该使用 Warning.extend(MyNewModuleWithWarnMethod)
,你可以使用 super
来获取将警告打印到 $stderr
的默认行为。
示例
module MyWarningFilter def warn(message, category: nil, **kwargs) if /some warning I want to ignore/.match?(message) # ignore else super end end end Warning.extend MyWarningFilter
你永远不应该重新定义 Warning#warn
(实例方法),因为那样将不再提供使用默认行为的方法。
warning gem 提供了方便的方式来自定义 Warning.warn
。
公共类方法
源
static VALUE rb_warning_s_aref(VALUE mod, VALUE category) { rb_warning_category_t cat = rb_warning_category_from_name(category); return RBOOL(rb_warning_category_enabled_p(cat)); }
返回一个标志,用于显示 category
的警告消息。支持的类别包括
:deprecated
-
弃用警告
-
将非空值赋值给
$,
和$;
-
关键字参数
等等。
-
:experimental
-
实验性功能
:performance
-
性能提示
-
形状变化限制
-
源
static VALUE rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag) { unsigned int mask = rb_warning_category_mask(category); unsigned int disabled = warning_disabled_categories; if (!RTEST(flag)) disabled |= mask; else disabled &= ~mask; warning_disabled_categories = disabled; return flag; }
为 category
设置警告标志。有关类别,请参阅 Warning.[]
。
源
static VALUE rb_warning_s_categories(VALUE mod) { st_index_t num = warning_categories.id2enum->num_entries; ID *ids = ALLOCA_N(ID, num); num = st_keys(warning_categories.id2enum, ids, num); VALUE ary = rb_ary_new_capa(num); for (st_index_t i = 0; i < num; ++i) { rb_ary_push(ary, ID2SYM(ids[i])); } return rb_ary_freeze(ary); }
返回支持的类别符号的列表。
公共实例方法
源
static VALUE rb_warning_s_warn(int argc, VALUE *argv, VALUE mod) { VALUE str; VALUE opt; VALUE category = Qnil; rb_scan_args(argc, argv, "1:", &str, &opt); if (!NIL_P(opt)) rb_get_kwargs(opt, &id_category, 0, 1, &category); Check_Type(str, T_STRING); rb_must_asciicompat(str); if (!NIL_P(category)) { rb_warning_category_t cat = rb_warning_category_from_name(category); if (!rb_warning_category_enabled_p(cat)) return Qnil; } rb_write_error_str(str); return Qnil; }
将警告消息 msg
写入 $stderr。Ruby 会为所有发出的警告调用此方法。警告可以包含 category
。
有关如何自定义此方法,请参阅 Warning
模块的文档。