Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'before_action' in a module

I would like to use 'before_action' in a module.

Unfortunately, I couldn't get it work.

I was googleing, but everything I found couldn't solve the problem.

My module file looks like the following:

module ShowController
  include SimpleController
  #before_action :set_object, only: [:show]

  def show
   set_object
  end
end

I would like to use the outcommented before_action line instead of the show method.

Therefore, I was trying to include the following modules:

  include AbstractController::Callbacks
  include ActiveSupport::Callbacks
  include ActiveSupport::Concern
  include ActiveSupport

Additionally, I tried to "require 'active_support/all'" or the core_ext.

The error_message I receive is:

 undefined method `class_attribute' for SimpleController::ShowController:Module

Finally, nothing worked out and I didn't find a solution.

like image 741
flp Avatar asked Jan 09 '15 18:01

flp


1 Answers

I think this is what you're trying to do:

class SomeController < ActionController::Base
  include SimpleController
end 

module SimpleController
  extend ActiveSupport::Concern

  included do
    before_action :set_object, only: [:show]
  end
end
like image 200
evanbikes Avatar answered Oct 07 '22 13:10

evanbikes