8

I am working on a rails engine and I have a problem with the helpers.

Apparently this is a known "problem" but there's not a lot of solutions out there. The problem is that I have an AuthenticationHelper which I want to access globally - but it's not working.

I've read that you could add a few lines to your init.rb but it does not seem to have any effect.

Any idea what the best way to make an application available in an engine?

EDIT: Fixed it- Just put the code (from the link) in the engine.rb instead.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Markus
  • 2,526
  • 4
  • 28
  • 35

3 Answers3

10

Put this code in engine.rb:

config.to_prepare do
  ApplicationController.helper(MyEngineHelper)
end
Brad Werth
  • 17,411
  • 10
  • 63
  • 88
3

To access main app helpers (ApplicationHelper) from engine's views I tried include this:

app/helpers/your_engine/application_helper.rb

module YourEngine
  module ApplicationHelper
    include ActionView::Helpers::ApplicationHelper
  end
end

It works, but once, when I restarted dev server, it throws me uninitialized constant ActionView::Helpers::ApplicationHelper, but I can't reproduce this exception.

EDIT

Removed this include and made this one:

lib/my_engine/engine.rb (it's inside engine)

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine
    config.to_prepare do
      ApplicationController.helper(ActionView::Helpers::ApplicationHelper)
    end
  end
end
Alex Fedoseev
  • 1,135
  • 11
  • 18
  • 1
    I had to change the .helper line in Rails 4.2 to this: ApplicationController.helper(::ApplicationHelper) ... That might even have worked with your first solution. – Allen Jul 01 '15 at 16:15
  • I follow this solution and application_helper works fine, but when I run `rails console`, I got "uninitialized constant ActionView::Helpers::ApplicationHelper (NameError)". Does someone knows the reason? – Bater Chen Dec 01 '21 at 06:48
0

Adding this just in case:

I had the same problem using the Administrate gem with Rails 7. I wanted to access my main app helper modules.

Simply adding helper all_helpers_from_path 'app/helpers' in Admin::ApplicationController solved this. You can find the official documentation here.

My file now looks like this:

module Admin
  class ApplicationController < Administrate::ApplicationController
    before_action :authenticate_admin_user!
    helper all_helpers_from_path "app/helpers"
  end
end

I found the answer here.

Gabriel Guérin
  • 430
  • 2
  • 13