Does a lot of before_action cause bad code style?

I am working on an application with a controller that has a lot of before_actions. Most of them are related to each other by the instance variables that they specify. For instance:

def first_action @first_variable = Something.new end def second_action if @first_variable @second_variable = Other.new end end 

The controller is as follows:

 class ExampleController < ApplicationController before_action :first_action, only: [:index, :show, :create] before_action :second_action, only: [:index, :show, :create] before_action :third_action, only: [:index, :show, :create] before_action :fourth_action, only: [:index, :show, :create] before_action :fifth_action, only: [:index, :show, :create] before_action :sixth_action, only: [:index, :show, :create] before_action :seventh_action, only: [:index, :show, :create] def index # some code end def show # some code end def create # some code end private # all of the before_action methods end 

It is very difficult for me to understand from my point of view. Each of these methods has a lot of code. In addition, there are controllers that inherit from this, and also use part or all of these actions.

I heard that it’s better to be explicit regarding loaded variables in each method, but this is:

 class ExampleController < ApplicationController def index first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end def show first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end def create first_action second_action third_action fourth_action fifth_action sixth_action seventh_action # some code end private # all of the before_action methods end 

It doesn't look much better. Is there a way to reorganize it for greater readability, or should I stick with the current solution?

+14
source share
2 answers

There is nothing wrong with having several before_actions, but it looks like you have a case where they can be assembled into a single action?

+6
source

Your current decision is in order. You can use like to avoid several method calls

 before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create] 
+29
source

Source: https://habr.com/ru/post/1259107/


All Articles