1

I have simple class with class's and private's methods

class XmlConnection

 def self.guitarmania
    request = HTTParty.get(site_url)
    handle_errors(request)
  end

 private

  def handle_errors(request)
    if request.code == 200
      request
    else
      raise 'Connection error'
    end
  end



end

when i call XmlConnection.guitarmania i get

NoMethodError: undefined method 'handle_errors' for XmlConnection:Class

How i can fix it?

2 Answers 2

2

When you're using a self. for a class method, all private methods also need to use self to be accessed from within it. The following will work:

class XmlConnection

 def self.guitarmania
    request = HTTParty.get(site_url)
    handle_errors(request)
  end

 private

  def self.handle_errors(request)
    if request.code == 200
      request
    else
      raise 'Connection error'
    end
  end
end

If all your methods will be class methods, you could wrap them all in a self to make it a bit more readable. This works exactly as above:

class XmlConnection
   class << self
     def guitarmania
        request = HTTParty.get(site_url)
        handle_errors(request)
      end

     private

      def handle_errors(request)
        if request.code == 200
          request
        else
          raise 'Connection error'
        end
      end
    end
end
Sign up to request clarification or add additional context in comments.

1 Comment

private in the first snippet does not declare self.handle_errors as private class method. Use private_class_method :handle_errors instead.
1

You have to define handle_errors on the class as well:

def self.handle_errors(request)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.