[英]How come methods under 'private' and 'protected' can always be called in models (rails)?
I tested, that they, in fact, don't work:我测试过,它们实际上不起作用:
class User < ActiveRecord::Base
def self.call_protected_method
protected_method
end
def self.call_private_method
private_method
end
protected
def self.protected_method
puts "protected_method"
end
private
def self.private_method
puts "private_method"
end
end
What i mean, by they don't work, is You can call all methods in this example.我的意思是,它们不起作用,是您可以调用此示例中的所有方法。 It doesn't matter if they are under private and/or protected.它们是否处于私有和/或受保护状态并不重要。
# in rails console:
User.call_protected_method # => protected_method
User.protected_method # => protected_method
User.call_private_method # => private_method
User.private_method # => private_method
Why is that?这是为什么? Whats the reason for ignoring 'private' and 'protected'?忽略“私有”和“受保护”的原因是什么?
UPDATE: my question isn't how to do this.更新:我的问题不是如何做到这一点。 My question is why doesn't this approach work in rails models!?我的问题是为什么这种方法在 Rails 模型中不起作用!?
You are trying to define a private class method, and that would not work with that syntax.您正在尝试定义一个私有类方法,这不适用于该语法。 You want private_class_method你想要private_class_method
Have a look at these answers, too: Ruby class with static method calling a private method?也看看这些答案: 带有静态方法调用私有方法的 Ruby 类?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.