[英]How to access private class methods in Rails
I have a class Initialization. 我有一个类的初始化。
I have a method send_mail which is a class method 我有一个方法send_mail这是一个类方法
def self.send_mail
a = user_stats
end
user_stats is a private method and when I try to call this method, it throws an error user_stats是一个私有方法,当我尝试调用此方法时,它将引发错误
class << self
private
def user_stats
true
end
end
When I tried accessing user_stats , 当我尝试访问user_stats时,
undefined method 'user_stats' for Initialization
Also tried 也尝试过
class << self
def self.send_mail
a = user_stats
end
private
def user_stats
true
end
end
Both of your approaches are correct, but in the latter you shouldn't use self
, cause you already define method in Initialization
's eigenclass: 两种方法都是正确的,但是在后一种方法中,您不应使用
self
,因为您已经在Initialization
的本征类中定义了方法:
class Initialization
class << self
def send_mail
a = user_stats
end
private
def user_stats
true
end
end
end
Initialization.send_mail
# => true
Your first approach also works for me: 您的第一种方法也对我有用:
class Initialization
def self.send_mail
a = user_stats
end
class << self
private
def user_stats
true
end
end
end
Initialization.send_mail
# => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.