hellomello
hellomello

Reputation: 8585

Ruby on Rails Private Methods?

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?

Upvotes: 13

Views: 6900

Answers (5)

Sohrab Vafa
Sohrab Vafa

Reputation: 1

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

Upvotes: -1

David H.
David H.

Reputation: 2862

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

Upvotes: 4

Nerve
Nerve

Reputation: 6851

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

Upvotes: 3

MrTheWalrus
MrTheWalrus

Reputation: 9700

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?

Upvotes: 12

Raindal
Raindal

Reputation: 3237

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.

Upvotes: 4

Related Questions