Unable to access private method from inner class?

Why can't I access the private check_url method in the code below from the encapsulated class 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 also tried using self.check_url and it did not work.

+8
ruby ruby-on-rails
source share
2 answers

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

Another problem is that you defined check_url as an instance method and called it in the class method. Move check_url to 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 
+9
source share

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

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

+3
source share

All Articles