krunal shah
krunal shah

Reputation: 16339

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

I am writing a rails engine.

I have two methods(authenticate and current_user) in the gem inside application controller. https://github.com/krunal/aadhar/blob/master/app/controllers/aadhar/application_controller.rb

I want 'authenticate' method should be available as a before_filter in parent rails application.

I want 'current_user' method should be available as a method and helper in parent rails application .

I don't know how can I achieve that.

Let say in my parent application, I have a posts controller. I want to use 'authenticate' and 'current_user' this way.

PostsController < ApplicationController
before_filter :authenticate

def index
  current_user.posts
end

Upvotes: 2

Views: 774

Answers (2)

krunal shah
krunal shah

Reputation: 16339

Reference - A way to add before_filter from engine to application

Steps

1) Created a new file authenticate.rb inside lib/aadhar/. authenticate.rb

2) Required authenticate.rb inside lib/aadhar.rb aadhar.rb

3) Added following lines in lib/aadhar/engine.rb engine.rb

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

4) Authenticate and current_user methods are now available in my parent rails application.

Upvotes: 1

Ryan Buckley
Ryan Buckley

Reputation: 106

You're using isolate_namespace in your engine (recommended) but that means you need to use the namespace within the parent application. So if you change it to:

PostsController < Aadhar::ApplicationController

You can access the authenticate and current_user methods. Keep in mind, you'll have to add

helper_method :current_user

in the controller to be able to access it from the view. I tried this and can confirm it works.

Upvotes: 1

Related Questions