【问题标题】:how can I provide engine methods available to parent rails application?如何提供可用于父 Rails 应用程序的引擎方法?
【发布时间】:2015-04-06 03:58:57
【问题描述】:

我正在编写一个 Rails 引擎。

我在应用程序控制器的 gem 中有两种方法(authenticate 和 current_user)。 https://github.com/krunal/aadhar/blob/master/app/controllers/aadhar/application_controller.rb

我希望 'authenticate' 方法应该在父 Rails 应用程序中作为 before_filter 提供。

我希望 'current_user' 方法应该在父 Rails 应用程序中作为方法和助手可用。

我不知道如何才能做到这一点。

假设在我的父应用程序中,我有一个帖子控制器。我想以这种方式使用 'authenticate' 和 'current_user'。

PostsController < ApplicationController
before_filter :authenticate

def index
  current_user.posts
end

【问题讨论】:

    标签: ruby-on-rails ruby gem rails-engines


    【解决方案1】:

    您在引擎中使用isolate_namespace(推荐),但这意味着您需要使用父应用程序中的命名空间。因此,如果您将其更改为:

    PostsController < Aadhar::ApplicationController
    

    您可以访问authenticatecurrent_user 方法。请记住,您必须添加

    helper_method :current_user
    

    在控制器中以便能够从视图中访问它。我试过了,可以确认它有效。

    【讨论】:

    • 是否可以在posts_controller.rb中不指定Aadhar::ApplicationController的情况下达到同样的效果
    • 我会将父应用程序application_controller.rb 更改为从您的引擎application_controller.rb 继承。但是,如果这太笨重,那么也许只需将引擎控制器中的功能移动到一个模块,您可以将其混入您的父母应用程序控制器。稍微不那么突兀的方法。因为从您的引擎应用程序控制器继承也将尝试使用引擎助手。所以这真的取决于你想要移动多少代码到引擎。
    【解决方案2】:

    参考 - A way to add before_filter from engine to application

    步骤

    1) 在 lib/aadhar/ 中创建了一个新文件 authenticate.rb。 authenticate.rb

    2) lib/aadhar.rb aadhar.rb 中需要的 authenticate.rb

    3) 在 lib/aadhar/engine.rb engine.rb 中添加以下行

    ActiveSupport.on_load(:action_controller) do
      include Aadhar::Authenticate
    end
    

    4) Authenticate 和 current_user 方法现在可以在我的父 Rails 应用程序中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多