This chapter explains refactoring techniques and cautionary points in Controller.
There is not much to describe, but this means Controller basically does nothing except related to HTTP Communication(request/response) handling. If your Controller is fat, the first goal is "Skinny controller, Fat model".
As a restate, this is my article on basic refactoring.
dev.to - Refactoring Guide for Rails Beginners
Code that can be written in Controller
- Methods related to HTTP Communication handling.
- e.g.
respond_to
,flash
,redirect_to
,render
,params.permit
etc.
- e.g.
- Simple CRUD methods.
- e.g.
new
,find
,save
,destroy
and so on.
- e.g.
- Call Model method or Service class method.
Where should other codes be placed? Basically, it's all in Model. Of course, if your team already have an implementation policy for Service classes, just follow that.
Common function
Basically place in application_controller.rb
.
For a specific namespace, create an application_controller.rb
such as app/controllers/admin/application_controller.rb
and inherit it.
Be careful of concerns
directory
If it is assumed that "only code that related HTTP Communication are placed in Controller", using app/controllers/concerns/
is no problem because the code amount will not be so large.
However, it is a little cautionary to use "concerns" directory when Controllers are not organized yet. Before start using "conserns", Controllers should be organized by moving code into Model or Service class.
Separate Actions for API (ajax)
If the Actions for API (ajax) are defined in the same controller, the code will be difficult to read. So separating API actions to other controller is good.
For example, they are often separated by directories such as
- If the normal Controller is
app/controllers/users_controller.rb
, - then the API Controller is
app/controllers/api/v1/users_controller.rb
.