Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access private method from inside class?

Why can't I access the check_url private method in the code below from a class encapsulated method?

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. I've also tried using self.check_url and it didn't work.

like image 837
user1049097 Avatar asked Nov 30 '11 00:11

user1049097


2 Answers

In Ruby, private methods cannot be called with an explicit receiver. So you cannot call self.check_url. Instead, just call check_url.

Your other problem is you defined check_url as an instance method, and called it in a class method. Move the check_url into the class << self scope:

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
like image 71
miaout17 Avatar answered Nov 02 '22 15:11

miaout17


check_url is defined as an instance method, and you're trying to access it from a class method (the method is not defined on the class, it's defined on an instance). Change def check_url to def self.check_url or include it in the class << self block.

Are you sure you're getting a private method error, or are you actually getting an undefined method error (both will be a NoMethodError but with different messages)?

like image 36
Martin Gordon Avatar answered Nov 02 '22 15:11

Martin Gordon