我测试过,他们实际上不起作用:
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
我的意思是,由于它们不起作用,您可以在此示例中调用所有方法。它们是否属于私人和/或受保护并不重要。
# 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
为什么?忽略“私人”和“受保护”的原因是什么?
更新:我的问题不是如何做到这一点。我的问题是为什么这种方法不适用于rails模型!?
答案 0 :(得分:1)
您正在尝试定义私有类方法,但这不适用于该语法。你想要private_class_method
也要看看这些答案:Ruby class with static method calling a private method?