Back

Rails engines

I recently discovered Rails Engines which is a great way to seperate code out of your application.

These are different to Ruby gems as they allow you to share Rails elements with the host application such as models, migrations, views etc.

There are a heap of tutorials online on how to create an engine, but here are some of my notes:

Full or Mountable?

Engines can be setup with a --full or --mountable flag.

Full means that the engine will work within the main app - whereas mountable means that the engine works alongside the main application.

Mountable is the best way in my opinion. In this mode everything is namespaced so that it doesn't clash with the main app. For example a Person model might be named EngineName::Person instead.

Some notes:

To create a mountable engine, I used this command:

rails plugin new filenet --mountable -T -d postgresql --dummy-path=spec/dummy

Adding the Engine to the host application

Adding an engine is as easy as adding it to the Gemfile. I did however reference the engine locally when I was developing so I could make changes in engine without needing to release a new version and bundle update on the host.

gem 'filenet', path: '../filenet'

Migrations

You can create Rails migrations within the engine as usual. When you want to copy these accross to the main app you can run:

rake engine_name:install:migrations

You will then need to run a migrate on the main app as usual.

Specs

Setting up engine with Rspec, Capybara and FactoryBot

Basically I followed this link above and got rspec and factory bot running. It also makes changes to the rake file so that any commands such as rake db:migrate are actually run on the spec/dummy app.

Spring

Because the engine isn't really an app, I needed to do the following so that spring was pointing to the dummy app.

In config/spring.rb, make sure you have the following: Spring.application_root='test/dummy'

And in test/dummy/config/spring.rb, make sure you have the following: Spring.application_root=''

I added the spring rspec commands gem , and generated the binstubs

bundle exec spring binstub rspec