Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple before_action calls bad code style?

I'm working on an app with controller that have lots of before_actions. Most of them are connected with each other by instance variables that they set. For example:

def first_action
  @first_variable = Something.new
end

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

Controller looks like this:

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's really hard to understand from mine point of view. Each of those method has lots of code. Additionaly there are controllers that inherits from this one and also use part or all of those actions.

I heard that it's better to be explicit about loaded variables in each method but this:

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

doesn't look much better. Is there a way to refactor it for more readability or should I stick with current solution?

like image 847
zeth Avatar asked Nov 01 '16 15:11

zeth


Video Answer


1 Answers

Your current solution is okay. You can use like to avoid multiple method calls

before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]
like image 100
Premanandh Selvakumarasamy Avatar answered Oct 08 '22 06:10

Premanandh Selvakumarasamy