访问Rails引擎application_controller中的current_user

时间:2016-06-13 14:08:06

标签: ruby-on-rails-4 rubygems rails-engines

我创建了一个Rails引擎来记录我的应用程序中的一些活动。在模型和视图级别一切正常,测试正在传递,并且视图在主机应用程序中可见。现在对于控制器...我只是无法访问主机,主ApplicationController在其中插入一个before_filter。

引擎内的app / controllers目录如下所示:

/app
  /controllers
    /storyteller
      /application_controller.rb

然后,在application_controller.rb中我添加了这个:

module Storyteller
  class ApplicationController < ::ApplicationController 

    before_action :save_current_user

    def save_current_user
      raise current_user.inspect # Doesn't raise
    end
  end
end

raise 'here' # No, doesn't raise anything too!

这样做......没有任何反应,甚至看起来这个文件根本没有加载。我阅读了大量的教程和文档,但从未使用它。

我想做的就是在主机应用的每个操作/路线上随处跟踪current_user,我错过了什么?

3 个答案:

答案 0 :(得分:0)

控制器应该继承ActionController::Base

e.g。

module Storyteller class ApplicationController < ActionController::Base # Put your code here end end

答案 1 :(得分:0)

尝试include块来声明您的before_action

e.g。

module Storyteller
  class ApplicationController < ActionController::Base

    included do
      before_action :save_current_user
    end

    def save_current_user
      raise current_user.inspect # Doesn't raise
    end
  end
end

答案 2 :(得分:0)

最后!通过在github上研究其他一些Gems来实现它...这就是我为控制器做的事情:

# Engine /app/controllers/storyteller/application_controller.rb
module Storyteller
  module ApplicationController 
    extend ActiveSupport::Concern

    included do 
      before_action :save_current_user

      def save_current_user
        UserRegistry.current_user ||= current_user
      end
    end
  end
end

我还必须将其添加到引擎设置中:

# /lib/storyteller/engine.rb
module Storyteller
  class Engine < ::Rails::Engine
    isolate_namespace Storyteller

    initializer "get into controllers" do |app|
      ActionController::Base.send :include, Storyteller::ApplicationController
    end
  end
end

希望这可以帮助某人......