Ruby-on-rails – Access Main App Helpers when overridings a Rails Engine View/Layout

rails-3.1rails-enginesruby-on-railsruby-on-rails-3.1

I have created a simple Rails Engine to provide some general functionality(photo gallery) to an application. I want to be able to override the standard _header partial so that the menu for the gallery matches that of my main application. In my header view I call a helper that is part of application_helpers (main app), but I keep getting "undefined method" errors. From what I can tell the main app application_helpers are not being included (obviously) when I override the engines application layout or its partials.

So my question is, how do I override an engine view in the main application, and get access to the main application helper methods? I would still need access to the engine helpers as well as not to screw up the engine functionality.

Do I need to override the controllers as well? seem like a lot just to get some helpers.

Thanks

Rails 3.1.3

Best Answer

check out this blog post: http://www.candland.net/2012/04/17/rails-routes-used-in-an-isolated-engine/ The author adds a method_missing definition to the application helper in order to access the parent application's helpers.

/config/initializers/blogit.rb

module Blogit
    module ApplicationHelper
      def method_missing method, *args, &block
        puts "LOOKING FOR ROUTES #{method}"
        if method.to_s.end_with?('_path') or method.to_s.end_with?('_url')
          if main_app.respond_to?(method)
            main_app.send(method, *args)
          else
            super
          end
        else
          super
        end
      end

      def respond_to?(method)
        if method.to_s.end_with?('_path') or method.to_s.end_with?('_url')
          if main_app.respond_to?(method)
            true
          else
            super
          end
        else
          super
        end
      end
    end
  end
Related Topic