Is it possible to include an unbuilt Rails Engine without using the Gemfile?

616 views Asked by At

This may be a bit of a contrived question, but I'm working on a Rails API and want to keep the API middleware stack minimal, while providing an OAuth endpoint that requires a few of the more complex middlewares. My thought was to make it into an engine, and include that engine in the application.

However, I thought there would be an easier way to create a Rails Engine than generating a new engine gem and including the gem in my Gemfile. Is there a way to just... require 'lib/engines/my_engine' from application.rb or something? I shouldn't need a gemspec just to include an unbuilt engine - I can put all the dependencies in the main app's Gemfile.

Really all I'm trying to do is get a separate middleware stack for a small set of routes!

1

There are 1 answers

0
mltsy On BEST ANSWER

I've discovered that an engine can be included just by requiring it as per the Rails::Engine documentation:

ensure that this file is loaded at the top of your config/application.rb (or in your Gemfile)

So I tried this, and it worked:

application.rb:

# after Bundler.require(...)
require_relative '../lib/engines/oauth_server/lib/oauth_server'

So that answers this question. And technically all that is required in this case, rather than a whole gem structure, is a file in a lib directory containing a class that inherits from Rails::Engine (it has to be in lib to ensure the adjacent app, config, vendor etc. directories will be included automatically if present). And of course a config/routes.rb file if you intend to actually use this engine for anything ;)

For instance, my engine (required above) just looks like this:

module OauthServer
  class Engine < ::Rails::Engine
    middleware.use ActionDispatch::Cookies
    middleware.use ActionDispatch::Session::CookieStore
    middleware.use ActionDispatch::Flash
  end
end

However, I also discovered that a Rails engine seems to inherit the middleware from the app it is included in, so I'm back to my original question, which someone has already asked previously: Build 2 middleware stacks in Rails app