Rails Engines allow functionality to be packaged as reusable components (mini-apps) that can be included in host Rails apps. An Engine is a gem that can provide routes, models, controllers, and other functionality to a host app. Popular Engines include Devise for authentication and RefineryCMS for content management. Engines are created using the rails plugin new command and have an app/ directory and other standard Rails structure. They are configured via an initializer and expose their routes to the host app. Engines are tested independently but require the host app for development. They can help achieve separation of concerns and allow functionality to be extracted and reused across apps using a component-based approach.
17. Engine Configuration
module Chat
class Engine < ::Rails::Engine
isolate_namespace Chat # !important
initializer 'chat.settings' do |app|
app.config.x.chat = OpenStruct.new(room: 'newbies')
end
end
end
Regular config/initilializers/* can also be used for configuration
18. Engine Routes
Setting the routes
Chat::Engine.routes.draw do
root 'rooms#index'
resources :rooms do
resources :messages, only: %i[create]
end
end
19. Engine Routes
Mounting from main app
Rails.application.routes.draw do
mount Chat::Engine, at: '/chat'
# other routes
end
main_app.resource_path
20. Engine Development
Starting a console
cd ./spec/dummy
./bin/rails console
Bundling on the host app
gem 'engine_name', path: '../path/to/engine'