无法从类内部访问私有方法?

时间:2011-11-30 00:18:03

标签: ruby-on-rails ruby ruby-on-rails-3.1

为什么我无法从类封装方法中访问以下代码中的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,但它没有用。

2 个答案:

答案 0 :(得分:10)

在Ruby中,无法使用显式接收器调用私有方法。所以你不能打电话给self.check_url。相反,只需致电check_url即可。

您的另一个问题是您将check_url定义为实例方法,并在类方法中调用它。将check_url移至class << self范围:

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

答案 1 :(得分:3)

check_url被定义为实例方法,并且您尝试从类方法访问它(该方法未在类上定义,它是在实例上定义的)。将def check_url更改为def self.check_url或将其包含在class << self块中。

您确定收到了私有方法错误,或者您实际上是否收到了未定义的方法错误(两者都是NoMethodError但邮件不同?)