Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between before_action and prepend_before_action in Rails?

My codebase contains callbacks like prepend_before_action :authenticate_api_user! and before_action :authenticate_api_v1_user! What is the difference between these two?

like image 213
Umesh Malhotra Avatar asked Apr 12 '18 07:04

Umesh Malhotra


1 Answers

Generally before_action runs before every action to a method and prepend_before_action does what it says. It just add your definition at index zero.

Here is a great use case to prove the same:

class ConfuseUsersController < ApplicationController
  prepend_before_action :find_user, only: [:update]
  prepend_before_action :new_user, only: [:create]

  before_action :save_and_render

  def update
  end

  def create
  end

  private

  def find_user
    @user = User.find(params[:id])
  end

  def new_user
    @user = User.new
  end

  def save_and_render
    persited = @user.persited?

    @user.assign_attributes(user_params)
    if @user.save
      redirect users_path(@user)
    else
      render (persited ? :edit : :new)
    end
  end
end
  • before_action :save_and_render this makes save_and_render to get called before every action.
  • prepend_before_action :find_user, only: [:update] This prepends find_user function to get called before save_and_render

Another example:

We have an ApplicationController where...

class ApplicationController < ActionController::Base
  before_action :one
  before_action :three
end

Now in any controller if we want to execute any other method for e.g. two before three you can use prepend_before_action like prepend_before_action :three, :two

class AdminsController < ApplicationController
  prepend_before_action :three, :two
end

Now before three gets executed two will get execute and then three for this specific method.

like image 133
Sravan Avatar answered Oct 11 '22 08:10

Sravan