Why Your Controller Methods Should be Private

in Ruby on Rails Tips

Most of your controller methods are public actions that display pages on your website. Your app’s routes will point to these methods and show the corresponding page (view). For example:

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def show
    @post = Post.find(params[:id])
  end

end

But hopefully you are keeping things modular and breaking up complexity into smaller methods. For example, you might want to perform some check before you allow the user to add a new post:

class PostsController < ApplicationController
  def new
    check_something
    @post = Post.new
  end

  def show
    @post = Post.find(params[:id])
  end

  def check_something
    redirect_to(root_path) and return if something
  end
end

This is great. BUT, you should be sure to make the check_something method private and make it accessible by defining it as a helper method:

class PostsController < ApplicationController
  helper_method :check_something

  def new
    check_something
    @post = Post.new
  end

  def show
    @post = Post.find(params[:id])
  end

private

  def check_something
    redirect_to(root_path) and return if something
  end
end

Why Make the Helper Methods Private?

So, why is it important to make methods like this private? Because you don’t want them to be accessible to your users. They can’t hit that method unless you have defined a route that points to it as an action. While unlikely, it’s possible that you might have such a route defined. Or, if you have some type of catch-all route defined, then this check_something method could actually be accessed by a user.

In most cases, this will be unlikely to happen. And if it does happen, it’s likely that little harm could be done. However, making these non-action methods privates also makes your code a bit more clear by declaring that these methods are NOT accessible via any routes. So, simply put, you should make the non-action methods private because it’s a best practice.

Comments on this entry are closed.

Previous post:

Next post: