In a Rails host app, how do you override a mounted engine's view and extend one of its model classes without forking the engine gem?
answer
- host app/views searched first
- same path: app/views/billing/...
- class_eval reopens, class may redefine
- decorators reloaded via to_prepare
- config.railties_order changes priority
basics
~20 sPut a template at the same path in the host, app/views/billing/invoices/index.html.erb, because host views are searched first. Extend a class by reopening it with class_eval from an autoloader-ignored override file loaded in config.to_prepare, or prefer an engine-provided extension point.
solid answer
~40 sEach engine prepends its `app/views` to the view paths, and the host's initializers run last, so the host's `app/views` wins. A file at `app/views/billing/invoices/index.html.erb` or `app/views/layouts/billing/application.html.erb` replaces the engine's, and `config.railties_order` can change that priority. For classes, the engines guide keeps decorators in `app/overrides`, tells the autoloader to ignore it, and loads each `*_override.rb` in `config.to_prepare` so it is reapplied after every development reload. The file must reopen with `Billing::Invoice.class_eval`, which loads the engine's class first; the `class` keyword risks defining one. A host file at `app/models/billing/invoice.rb` instead shadows the engine's file entirely. Prefer configuration the engine exposes, such as a `mattr_accessor`, over either.
code
ruby · 9 lines# config/application.rb (host)
overrides = "#{Rails.root}/app/overrides"
Rails.autoloaders.main.ignore(overrides)
config.to_prepare do
Dir.glob("#{overrides}/**/*_override.rb").sort.each do |override|
load override
end
endgo deeper
Know that a host template at the same path, app/views/billing/..., replaces the engine's view.
Explain why host views win (prepend order) and why decorators use class_eval and to_prepare rather than the class keyword and an initializer.
Weigh decorators, shadowing and extension points against upgrade cost, and back every override with a host test.
For engines your teams own, budget for designed extension points so the host never needs to decorate internals.
## Overriding views: path precedence Every engine has an `add_view_paths` initializer that, once Action Controller and Action Mailer load, **prepends** the engine's `app/views` to the view paths. Initializers run in railtie order with the application last, so the host prepends its own `app/views` after every engine and ends up first in the lookup list. The consequence is simple: to replace an engine template, create a file with the **same relative path** in the host. - `Billing::InvoicesController#index` renders `billing/invoices/index`, so the host file is `app/views/billing/invoices/index.html.erb`. - Partials follow the same rule: `app/views/billing/invoices/_invoice.html.erb`. - The engine's layout is `layouts/billing/application`, overridable at `app/views/layouts/billing/application.html.erb`. - Mailer templates override the same way under `app/views/billing/<mailer_name>/`. To change the order, set `config.railties_order` in the host, for example `[Billing::Engine, :main_app, :all]`, which puts the engine's files ahead of the application's. **Upgrade cost.** An overridden template is a copy. When the engine renames an instance variable or a partial's local, the copy keeps rendering the old contract. Override the smallest partial that does the job and re-diff overrides on every engine upgrade. ## Extending classes: three techniques | Technique | How | Trade-off | |---|---|---| | Decorator file | `Billing::Invoice.class_eval do ... end` in `app/overrides/models/billing/invoice_override.rb` | Keeps the engine's class and adds to it; must be reloaded with the code | | Shadowing file | Host defines `app/models/billing/invoice.rb` | The host's file wins and the engine's is not loaded, so the host owns the whole class | | Engine extension point | Engine exposes `Billing.payer_class = "Employee"` or a documented hook | Needs the engine author's cooperation, but survives upgrades | ### Decorators, as the engines guide sets them up 1. Keep overrides in `app/overrides`, a folder that does not follow the autoloader's file-to-constant naming (`invoice_override.rb` does not define `InvoiceOverride`). 2. Call `Rails.autoloaders.main.ignore(overrides)` in `config/application.rb` so the autoloader neither expects constants there nor eager-loads it. 3. In `config.to_prepare`, `load` every `*_override.rb`. In development the engine's classes are reloaded on code changes, which discards the decoration; `to_prepare` runs again after each reload and reapplies it. In production it runs once at boot. The override must **reopen** the class. `Billing::Invoice.class_eval` references the constant, which loads the engine's definition first and raises `NameError` if it is missing. The guide warns that the `class` keyword would define the class if it were not already in memory; and `class Billing::Invoice < ApplicationRecord` written in a host file names the host's `::ApplicationRecord`, which mismatches the engine's `Billing::ApplicationRecord` superclass and raises `TypeError` once the engine's class is loaded. ### Shadowing If the host puts a file at `app/models/billing/invoice.rb`, both the host and the engine have a file for `Billing::Invoice`. The autoloader loads the one from the first root directory, which is the host's, and ignores the engine's. The engines guide uses this with `ActiveSupport::Concern`: the engine keeps its model body in a concern, and the host's replacement class includes that concern and adds its own methods. Without such a concern, shadowing means copying the engine's whole class. ## Preferring extension points Decorators reach into code the engine does not promise to keep stable. For an engine you own, as with billing extracted from an HR monolith, design the seams in: - a configuration attribute for host classes, `mattr_accessor :payer_class` read with `constantize`, set by the host in an initializer; - partials meant to be replaced, documented as such; - explicit hooks (a callback or a notification) for behaviour the host must add. ## Common mistakes - Copying the engine's whole template directory into the host "to be safe", which freezes every screen at the old version. - Putting decorators directly in `config/initializers`: the autoloading guide says initializers cannot refer to reloadable constants, and a decoration applied once would not survive a development reload anyway. - Overriding a model by shadowing its file without re-including the engine's behaviour, which deletes associations and validations the engine relies on. - Decorating private engine methods whose names are not part of any documented API; these change in minor releases. - Forgetting that `prepend` with `super` is often clearer than redefining a method in `class_eval`, because the engine's original stays callable. ## Checklist - Override views at the same relative path; keep copies small. - Use `class_eval` or `prepend` from an ignored folder loaded in `to_prepare`; never the bare `class` keyword. - Add a test in the host that exercises each override, so an engine upgrade that breaks it fails in CI.
- Why does the override folder have to be ignored by the autoloader?The autoloader maps `app/overrides/models/billing/invoice_override.rb` to a constant such as `Models::Billing::InvoiceOverride` and expects the file to define it. A decorator defines no such constant, so eager loading would fail. Ignoring the folder and loading the files yourself avoids that.
- How would you make an override break loudly when the engine changes?Cover it with a host test that renders the overridden view and calls the added methods, and pin the engine version so upgrades are deliberate. Reviewing each override against the engine's diff on upgrade catches renamed locals and methods.
- Engine views can only be changed by forking the gem
- A host override must live under app/views/invoices without the namespace
- Reopening with the class keyword is as safe as class_eval for engine classes
- Decorators loaded once from an initializer survive development reloads
- Engine views always take precedence over the host's