Reputation: 4032
So, with all the metaprogramming stuff in ruby (using 1.9.3), I guess there is a method which returns the current visibility.
Lets assume it is called visibility
.
class Foo
puts visibility
# => "public"
private
puts visibility
# => "private"
end
So, whats visibility
- how can I get the current visibility the ruby interpreter uses when he finds new methods definitions?
Upvotes: 2
Views: 255
Reputation: 1699
AFAIK, there isn't a ready to use method. You could implement one, however, with something along the lines of (untested)
class Class
def visibility
define_method(:__visibility_discovery__) { }
visibility =
if protected_method_defined? :__visibility_discovery__
"protected"
elsif private_method_defined? :__visibility_discovery__
"private"
else
"public"
end
remove_method :__visibility_discovery__
end
end
Upvotes: 1
Reputation: 2034
In Ruby, you have three different levels of visibility for instance methods.
Methods default to public
, which is what you are probably used to. You always have access to this method if you have access to the object.
private
and protected
are similar. They can only be accessed by the class and subclasses. The difference is that public
methods cannot be called with an explicit receiver. What that means is you cannot call another method's private
function from another instance of the same class, while protected
can.
So if you need methods to be available outside of your class, stick to the default visibility of public
. If your method needs to be accessed by any instance of that class, such as some custom comparison logic, use protected
. And if your method is anything that should not be visible outside an instance of that class, use private
.
To actually answer your question, visbility
is a method that returns the current state of visibility - whether it is public
, private
, or protected
.
Upvotes: 0