Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use private method in Rails?

I'm not entirely sure about the concept of private method in rails, and when and how to use it. Are there any rules? what are the differences between private vs public, vs protected? For example, in the following example, why is private method being used here instead of the other two methods. Is it best practice to always use private method for user generated input? Please enlighten me. Many thanks!

class PostsController < ApplicationController

def index
  @posts = Post.all.order("created_at DESC")
end

def new
 @post = Post.new
end

def create
 @post = Post.new(post_params)
  if @post.save
 redirect to @post
 else
  render 'new'
 end
end

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

private

def post_params
  params.require(:post).permit(:title, :body)
 end
end
like image 513
York Wang Avatar asked Aug 12 '16 21:08

York Wang


2 Answers

In the Rails ActionController context, public methods of a controller class are exposed to web server through Rails routes. You can define a route to the public methods of the class and use them as controller actions.

However you can not define routes to private methods. They are designed as internal helper methods and there is no way to expose them to web server.

This leads to a basic convention in your controllers: Define each of your controller action as a public method, define routes for each of them and ether define views corresponding the actions or chain each action to another action or view. Use private methods or other classes for your helper methods or other components.

Of course these are conventions. You can make all your methods in controllers public if you're sure that no one would define routes to these methods or exposing them to the clients won't be harmful (as exposing sensitive information, creating vulnerability or just looking silly).

like image 81
infiniteRefactor Avatar answered Sep 30 '22 19:09

infiniteRefactor


Because generally scope is a good thing.

It's one of the reasons you use classes to group methods together.

When those methods need to be called either as class levels methods or instance methods they need to be public.

This is also more of a core ruby concept than anything to do with rails.

However when those methods start to have a lot of code in them, it is a good practice to extract the details into other methods which are only called from the public methods within the class. The methods you extract are private methods.

As for protected it's more complicated, relates to inheritance and is rarely actually needed.
See separate questions such as Why does Ruby have both private and protected methods? which states protected methods can be called by any instance of the defining class or its subclasses.

like image 35
Michael Durrant Avatar answered Sep 30 '22 19:09

Michael Durrant