Rails Routes used in an Isolated Engine

Dusty Candland | | engines, rails, routes

The Problem

I have a rails application an want to add a blog engine to it. In this case the blogit engine. Things are working well until the layout is rendered. It uses the parent applications layout, which is what I want, but because it’s an isolated engine, it doesn’t have access to any of the parent applications helpers, including url helpers.

My Solution

If there’s a better way, please post in the comments.

In the engines config block, I open it’s application helper and add a method_missing definition. Then I check the main_app helper, which is added when the engine is mounted, for a matching helper method, if found use it.

/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
...

As a side note, the engine layout can be specified in /app/views/layouts/blogit/application.html.haml.

Gotchas

root_path and root_url are defined for the engine, so those still need to be handled differently. This issue could happend for any routes that overlap.

(main_app||self).root_path

And the other way if you want to link to the engines root_path. blogit is the engine_name.

(blogit||self).root_path

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: