I’ve been having this bothering recurring theme; let’s just say, I have a class which defines an instance method and a protected class method. The instance method must call the class method. In order to do so, I kind of have to break the visibility rule and use the dangerous ‘send’ function. Something like this:
class Bang
def instance_bang
self.class.send(:class_band)
end
protected
def self.class_bang
puts "bang"
end
end
I find this awful, since the class method should be used inside the class scope, therefore should remain visible and callable within it, right? Is there an alternative way to use class methods in instance methods with needing to rely on the “send” function and therefore not break visibility?
UPDATE:
Following Sergio Tulentsev’s response (thx for the correction), I’ll update my concern with a code snippet that sums up my concerns of the method visibility being taken into account while still inside the scope where it has been defined.
class Bang
def instance_bang
private_bang = 1
self.private_bang(private_bang)
end
private
def private_bang(p)
puts "bang"
p
end
end
Calling Bang.new.instance_bang will raise an Exception unless you use send on that private_bang call (this time I checked it 🙂 ).
EDIT: Answering the updated question
It is forbidden to call private methods with explicit receiver. You either have to use implicit receiver (
private_bang, withoutself) or usesend. Please see my another answer for more information.By the way, the original question is about calling class instance methods from instance methods. Your clarification doesn’t include that. But if that’s still true, you have to use
self.class.sendor make the method public (so that you can use explicit receiver).