Rendering Engine Partials on the Main App
As part of the dashboard feature of a web app, I needed to render partials that provide an overview or summary for a particular business area (implemented as an engine). I could hardcode the render
calls, but because the engines share common functionality or characteristics, I was able to use a helper function to test a particular partial’s existence and render it accordingly.
As an example, both my Project and Inventory engines have financial information. I created dashboard folders under the views folder on both engines, and then created _financial.html.erb
partials under views/dashboard. The dashboard folder for other engines may have the same financial partial, or may contain other partials such as _calendar.html.erb
, but all I need is for the engines to follow the same folder structure.
Back on my main app’s helpers\application_helper.rb
, I have the following method:
1
2
3
4
5
6
7
8
9
# engine_name: name of engine, string
# info_kind: financial, calendar, etc
def show_engine_partial(engine_name, info_kind)
if lookup_context.exists?("dashboard/#{info_kind}", prefixes = [engine_name], partial = true)
render(partial:"#{engine_name}/dashboard/#{info_kind}")
end
end
Line 5 of the code above uses lookup_context
, which is a method of ActionView. For a good explanation of how Rails finds partials and templates, see this post by Andy Wang.
The dashboard view on the main app is responsible for iterating through the available engines and passing the type of information (financial, calendar, etc) it needs. I wrote about how we manage engines and routes here.