Ruby/Rails syntax
  • Index
  • chap 1
  • chap 2
  • chap 3
  • chap 4
  • Enterprise Rails - big picture
  • Nokogiri
  • ActiveRecord - 進階功能
  • pack & unpack
  • performance
  • rails engine
  • jsonb / json / hstore
  • Deploy
  • Polymorphism/Polymorphic Associations
  • relationship
  • rvm / ENV
  • Auth
  • DB related
  • TODO N+1
  • SQL view
  • module
  • api + create-react-app
  • ONE_LINE
  • Delete & destroy association
Powered by GitBook
On this page
  • Engines & plugins
  • Generating an engine
  • Base class for the engine
  • When Constants aren't Missed
  • Require in host's gem file

Was this helpful?

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] appdir 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_namespaceIsolates 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, yourenginearticle, 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.

PreviousperformanceNextjsonb / json / hstore

Last updated 5 years ago

Was this helpful?