为什么我不能从类封装的方法中访问下面代码中的check_url私有方法?
class Link < MyModel # whitelist fields for security attr_accessible :is_valid,:url # validations validates :is_valid,:inclusion => { :in => [true,false] } validates :url,:presence => true # =============================================================== # = class methods (accessible from outside without an instance) = # =============================================================== class << self def is_url_valid(url) unless link = Link.find_by_url(url) link = Link.create!(:url => url,:is_valid => check_url(url)) end link.is_valid end end # ===================== # = Private functions = # ===================== private # Checks if url is broken def check_url(url) # do stuff end end
PS.我也尝试过使用self.check_url但它没有用.
解决方法
在Ruby中,不能使用显式接收器调用私有方法.所以你不能打电话给self.check_url.相反,只需调用check_url.
您的另一个问题是您将check_url定义为实例方法,并在类方法中调用它.将check_url移动到类<<自我范围:
class << self def is_url_valid(url) unless link = Link.find_by_url(url) link = Link.create!(:url => url,:is_valid => check_url(url)) end link.is_valid end private # Checks if url is broken def check_url(url) # do stuff end end