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.
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
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)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With