Skip to content

Commit d8f25bf

Browse files
author
Charlie Somerville
committed
add method visibility predicate methods
1 parent 6c37a57 commit d8f25bf

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

proc.c

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,6 +1076,31 @@ method_eq(VALUE method, VALUE other)
10761076
return Qtrue;
10771077
}
10781078

1079+
static rb_method_flag_t
1080+
mvisi(VALUE method)
1081+
{
1082+
Check_TypedStruct(method, &method_data_type);
1083+
return ((struct METHOD *)DATA_PTR(method))->me->flag & NOEX_MASK;
1084+
}
1085+
1086+
static VALUE
1087+
method_public_p(VALUE method)
1088+
{
1089+
return (mvisi(method) == NOEX_PUBLIC) ? Qtrue : Qfalse;
1090+
}
1091+
1092+
static VALUE
1093+
method_protected_p(VALUE method)
1094+
{
1095+
return (mvisi(method) == NOEX_PROTECTED) ? Qtrue : Qfalse;
1096+
}
1097+
1098+
static VALUE
1099+
method_private_p(VALUE method)
1100+
{
1101+
return (mvisi(method) == NOEX_PRIVATE) ? Qtrue : Qfalse;
1102+
}
1103+
10791104
/*
10801105
* call-seq:
10811106
* meth.hash -> integer
@@ -2339,6 +2364,9 @@ Init_Proc(void)
23392364
rb_cMethod = rb_define_class("Method", rb_cObject);
23402365
rb_undef_alloc_func(rb_cMethod);
23412366
rb_undef_method(CLASS_OF(rb_cMethod), "new");
2367+
rb_define_method(rb_cMethod, "public?", method_public_p, 0);
2368+
rb_define_method(rb_cMethod, "protected?", method_protected_p, 0);
2369+
rb_define_method(rb_cMethod, "private?", method_private_p, 0);
23422370
rb_define_method(rb_cMethod, "==", method_eq, 1);
23432371
rb_define_method(rb_cMethod, "eql?", method_eq, 1);
23442372
rb_define_method(rb_cMethod, "hash", method_hash, 0);

test/ruby/test_method.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,4 +551,34 @@ def x
551551
}, bug8100, timeout: 2
552552
rescue Timeout::Error
553553
end
554+
555+
class MethodVisibilityClass
556+
def pub
557+
end
558+
protected
559+
def prot
560+
end
561+
private
562+
def priv
563+
end
564+
end
565+
566+
def test_method_visibility
567+
o = MethodVisibilityClass.new
568+
pub = o.method(:pub)
569+
prot = o.method(:prot)
570+
priv = o.method(:priv)
571+
572+
assert pub.public?
573+
refute pub.protected?
574+
refute pub.private?
575+
576+
refute prot.public?
577+
assert prot.protected?
578+
refute prot.private?
579+
580+
refute priv.public?
581+
refute priv.protected?
582+
assert priv.private?
583+
end
554584
end

0 commit comments

Comments
 (0)