runub
runub

Reputation: 199

Pass all class methods to another function in Ruby on Rails

I have made the following validation method:

  def if_admin(&block)
       if @current_user.administrator?
           yield
       else
           redirect_to '/go_away'
       end
  end

and i find my classes are increasingly looking like:

class Foo < ApplicationsController

    def index
        if_admin do
              .....
        end
    end
    def show
        if_admin do
              .....
        end
    end
    def new
        if_admin do
              .....
        end
    end
    def edit
        if_admin do
              .....
        end
    end
    .......
end

I want to know if there is anything similar to before_action which would pass the method into the if_admin method, thus DRYing up the code?

Upvotes: 0

Views: 43

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

Just like you wrote, there is before_action. You can use it like this:

class Foo < ApplicationsController
  before_action :if_admin
  # ...
  private
  def if_admin
    redirect_to '/go/away' unless @current_user.administrator?
  end
end

Upvotes: 1

Related Questions