2

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
krunal shah
  • 16,089
  • 25
  • 97
  • 143

2 Answers2

1

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.

Ryan Buckley
  • 106
  • 3
  • Is it possible to achieve the same without specifying Aadhar::ApplicationController in posts_controller.rb – krunal shah Feb 06 '15 at 14:42
  • I would change the parent apps `application_controller.rb` to inherit from your engines `application_controller.rb`. But if that's too clunky, then maybe just move the functionality in the engines controller to a module that you can mixin to your parents app controller. Slightly less obtrusive approach. Because inheriting from your engines app controller will also try to use the engines helpers. So it really depends how much code you wanna move to the engine. – Ryan Buckley Feb 06 '15 at 17:41
1

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.

Community
  • 1
  • 1
krunal shah
  • 16,089
  • 25
  • 97
  • 143