rails engine
Engines & plugins
Common: [1]lib
dir, [2]generated using rails plugin new
Difference: [1]engine is considered a "full plugin" by Rails, [2]Engines can be isolated from host apps.
Generating an engine
rails plugin new blorgh --mountable
--full
: [1] app
dir tree, [2]config/routes.rb
, [3] lib/your_engine/engine.rb
(similar to config/application.rb
)
--mountable
: --full
+ [1]Asset manifest files (application.js
and application.css
), [2]namespaced ApplicationController, ApplicationHelper, layout view template, config/routes.rb
, [3] Namespace tolib/your_engine/engine.rb
, [4] mount the engine inside the dummy test
Base class for the engine
Base class = lib/blorgh/engine.rb
module Blorgh
class Engine < ::Rails::Engine # inheriting from the Rails::Engine class, this will let rails know how to deal with this.
isolate_namespace Blorgh
end
end
isolated_namespace
Isolates the controllers, models, routes, etc into own namespace, away from similar components inside the app. Without this, the engine's helpers would be included in an app's controllers.
Create Article model/controller: YourEngine::Article
, your
engine
article
, YourEngine::ArticlesController
,
When Constants aren't Missed
# app/models/flight_model.rb
class FlightModel
end
# The above will be overridden by each airplane
# app/models/bell_x1/flight_model.rb
module BellX1
class FlightModel < FlightModel
end
end
# app/models/bell_x1/aircraft.rb
module BellX1
class Aircraft
def initialize
@flight_model = FlightModel.new # which FlightModel??
end
end
end
Ambiguous can be prevent by
# 1. explicit definition!!
module BellX1
class Plane
def flight_model
@flight_model ||= BellX1::FlightModel.new
end
end
end
# 2. require_dependency
require_dependency 'bell_x1/flight_model'
module BellX1
class Plane
def flight_model
@flight_model ||= FlightModel.new
end
end
end
Require in host's gem file
In host app's gemfile: gem 'your_engine', path: 'engines/your_engine'
This will require lib/your_engine.rb
.
This file requires lib/your_engine/engine.rb
, and defines a base module called YourEngine
.
Last updated
Was this helpful?