kernel.c: add `__method__`; ref
MODIFY
mrbgems/mruby-kernel-ext/src/kernel.c
mrbgems/mruby-kernel-ext/src/kernel.c
#include <mruby/range.h>
#include <mruby/string.h>
#include <mruby/numeric.h>
+#include <mruby/proc.h>
#include <mruby/presym.h>
static mrb_value
@@ -64,6 +65,27 @@ mrb_f_caller(mrb_state *mrb, mrb_value self)
return mrb_ary_new_from_values(mrb, n, RARRAY_PTR(bt)+lev+1);
}
+/*
+ * call-seq:
+ * __method__ -> symbol
+ *
+ * Returns the called name of the current method as a Symbol.
+ * If called outside of a method, it returns <code>nil</code>.
+ *
+ */
+static mrb_value
+mrb_f_method(mrb_state *mrb, mrb_value self)
+{
+ mrb_callinfo *ci = mrb->c->ci;
+ ci--;
+ if (ci->proc->e.env->tt == MRB_TT_ENV && ci->proc->e.env->mid)
+ return mrb_symbol_value(ci->proc->e.env->mid);
+ else if (ci->mid)
+ return mrb_symbol_value(ci->mid);
+ else
+ return mrb_nil_value();
+}
+
/*
* call-seq:
* __callee__ -> symbol
@@ -246,6 +268,7 @@ mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
mrb_define_module_function(mrb, krn, "fail", mrb_f_raise, MRB_ARGS_OPT(2));
mrb_define_module_function(mrb, krn, "caller", mrb_f_caller, MRB_ARGS_OPT(2));
+ mrb_define_method(mrb, krn, "__method__", mrb_f_method, MRB_ARGS_NONE());
mrb_define_method(mrb, krn, "__callee__", mrb_f_callee, MRB_ARGS_NONE());
mrb_define_module_function(mrb, krn, "Integer", mrb_f_integer, MRB_ARGS_ARG(1,1));
#ifndef MRB_NO_FLOAT

MODIFY
mrbgems/mruby-kernel-ext/test/kernel.rb
mrbgems/mruby-kernel-ext/test/kernel.rb
@@ -37,27 +37,30 @@ assert('Kernel.caller, Kernel#caller') do
assert_raise(TypeError) { c.new.baz(nil) }
end
-assert('Kernel#__callee__') do
+assert('Kernel#__method__') do
c = Class.new do
- def m1; __callee__ end
- define_method(:m2) {__callee__}
+ def m1; __method__ end
+ define_method(:m2) {__method__}
alias m3 m1
alias_method :m4, :m2
end
assert_equal(:m1, c.new.m1)
assert_equal(:m2, c.new.m2)
- assert_equal(:m3, c.new.m3)
- assert_equal(:m4, c.new.m4)
+ assert_equal(:m1, c.new.m3)
+ assert_equal(:m2, c.new.m4)
+end
+assert('Kernel#__callee__') do
c = Class.new do
- [:m1, :m2].each do |m|
- define_method(m) do
- __callee__
- end
- end
+ def m1; __callee__ end
+ define_method(:m2) {__callee__}
+ alias m3 m1
+ alias_method :m4, :m2
end
assert_equal(:m1, c.new.m1)
assert_equal(:m2, c.new.m2)
+ assert_equal(:m3, c.new.m3)
+ assert_equal(:m4, c.new.m4)
end
assert('Kernel#Integer') do

kernel.c: add `__method__`; ref #4468