ruby-on-rails – 无法从类内部访问私有方法?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 无法从类内部访问私有方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么我不能从类封装的方法中访问下面代码中的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
原文链接:https://www.f2er.com/ruby/270765.html

猜你在找的Ruby相关文章