Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Engine With Isolated Namespace Sharing a Layout

I have a Rails Engine that I'd like to share a layout from the container application. I'd like to support all the URL helpers from the main app's layout(s) to make integration trivial. That is to support layouts with helpers from the container app:

= link_to "Signup", new_user_path
= link_to "Login", new_user_path
...

This causes:

undefined local variable or method `new_user_path' for #<#:0x007f9bf9a4a168>

I can fix it by changing the application.html (in the container app) to:

= link_to "Signup", main_app.new_user_path
= link_to "Login", main_app.new_user_path

But the goal is to make it so integrating the engine doesn't require users to make changes to the existing functioning application.html.

I believe I can also fix the errors by removing isolate_namespace Example from lib/example/engine.rb, but that breaks nearly everything in the engine.

Any way to allow container app helpers and explicitly namespace my engines helpers to avoid conflict? (i.e. using example.root_path instead of root_path)?

like image 825
Kevin Sylvestre Avatar asked Jul 30 '15 22:07

Kevin Sylvestre


1 Answers

Have a look at this: https://github.com/rails/rails/blob/a690207700d92a1e24712c95114a2931d6197985/actionpack/lib/abstract_controller/helpers.rb#L108

You can include your helpers from your engine in your host app.

module Blargh
  class Engine < ::Rails::Engine
    isolate_namespace Blargh

    config.to_prepare do


      # application helper
      ApplicationController.helper(Blargh::ApplicationHelper)
      # any other helper
    end
  end
end

This way you can use your helper in your rails host without problems. Of course there is no real namespacing this way, thus if a user of your engine names a new helper method the same as your helper method, it will clash.

Does that answer your question?

like image 93
Holger Frohloff Avatar answered Nov 10 '22 01:11

Holger Frohloff