Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Rails mountable engine not loading helper methods correctly?

I've built a rails gem that mounts as an engine.

The engine is scoped to it's own namespace.

In the engine, there's an MyEngine::ApplicationHelper module which adds a bunch of view helper methods.

In my application layout, I refer to some of these methods.

When I first load any of the pages in development mode I get a NoMethodError, complaining that the method (defined in the gem's ApplicationHelper) doesn't exist.

Once I edit ApplicationController within my app, the problem corrects itself.

Something tells me this is down to the recent changes in Rails's auto-loading; I'm using Rails 3.2.2

I can't for the life of me work out why this isn't working properly though :/

like image 386
bodacious Avatar asked Mar 21 '12 17:03

bodacious


People also ask

What is Rails helper method?

What are helpers in Rails? A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .

What is engine in Ruby on Rails?

1 What are Engines? Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the Rails::Application class inheriting a lot of its behavior from Rails::Engine .


2 Answers

I think the Rails guides has the answer here.

To include that particular helper from your Engine in your app:

class ApplicationController < ActionController::Base
  helper MyEngine::ApplicationHelper
end

To include all helpers from your Engine in your app:

class ApplicationController < ActionController::Base
  helper MyEngine::Engine.helpers
end
like image 197
Josh W Lewis Avatar answered Sep 18 '22 17:09

Josh W Lewis


To load the engine's GemName::ApplicationHelper to be used in the views of the engine itself, I added following to the engine.rb:

module GemName
  class Engine < ::Rails::Engine
    isolate_namespace GemName

    initializer 'local_helper.action_controller' do
      ActiveSupport.on_load :action_controller do
        helper GemName::ApplicationHelper
      end
    end
  end
end
like image 35
rya brody Avatar answered Sep 18 '22 17:09

rya brody