13

If I'm writing a private method, does rails think that every method under the word private is going to be private? or is it supposed to be only private for the first method?

  private

    def signed_in_user
      redirect_to signin_url, notice: "Please sign in." unless signed_in?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end 

does that mean signed_in_user and correct_user is private? or just signed_in_user? Does that mean whenever I need to write private methods, it should be at the end of my file now?

5 Answers 5

12

Yes, each method after the private keyword will be private. If you want to change back to defining non-private methods, you can use a different keyword, like public or protected.

See Where to place private methods in Ruby?

4

Yes all the methods under private are private. Usually you will, indeed, find those methods at the bottom of your file.

But you can "stop" this by writing another keyword like protected and then all the methods following would be protected.

4

Or you can even define your access control in this way too, listing your methods as arguments to the access control functions (public, protected, private):

class SomeClass
    def method1
        ...
    end

    def method2
        ...
    end

    def method3
        ...
    end
    # ... more methods def

    public    :method1, method4
    protected :method3
    private   :method2
end
3

As others have written, Every method that follows the private keyword immediately is private in Ruby. This is plain Ruby syntax and has nothing to do with rails.

private
  .....
def pvt_meth_1
  .....
end

def pvt_meth_2
  .....
end

public

def pub_meth_1
  ......
end
-1

It works the same way as c++ private, public tags, so yes both of them will be private

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.