如何提供父 rails 应用程序可用的引擎方法?

how can I provide engine methods available to parent rails application?

我正在编写一个 rails 引擎。

我在 gem 内部应用程序控制器中有两种方法(验证和 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

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

PostsController < Aadhar::ApplicationController

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

helper_method :current_user

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

参考 - 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) 我的父 rails 应用程序现在可以使用身份验证和 current_user 方法。