We wanted to open-source Rearview so that it could easily be used by the community. When we were discussing how to best do that, we knew our solution had to be as adaptable as possible. It needed to answer questions like:
How am I going to separate configuration from code? For example you might be using mysql but typically you would want your users to select any Rails supported database. Or maybe you use Capistrano for deployment with recipes and settings specific to your infrastructure.
What about gems that may not be appropriate for some users? This problem can occur with instrumentation like NewRelic and AirBrake. You do not want to impose them on all your users, but these might be required for others. Users should easily be able to add gems and features independent of the engine.
How can I create well-defined extension points for my application? For example even though you open source most of your code, there may be some code you want to keep internal. You also want to make it easy for other users to customize the application.
These questions can be answered with Rails engines.
Introduction to Engines
Rails engines are really just normal Rails applications that can be embedded into another Rails applications, referred to as the engine host. An engine can provide views, models, controllers, helpers, and other logic in any combination or amount as is warranted. The Rails guides refers to an engine as a “miniature application”. I find this statement misleading. An engine can be as small or as big as you want.
With that in mind, before we get into using Rails engines to build stand-alone applications, I’d like to cover some of the common use cases for Rails engines.
Common Use Cases For Engines
Sometimes its useful to create an engine that can be embedded as a miniature application inside another Rails project. For example, Resque is a Ruby based library for creating background jobs. Resque includes resque-web, a Rails engine providing an admin user interface for managing Resque queues. Although you can deploy resque-web by itself, as we do at LivingSocial, in smaller environments it might make sense to deploy it embedded within another Rails application.
Plug-in For Other Rails Applications
Devise is a authentication framework that is meant to be integrated into a pre-existing Rails project, and not intended to run stand alone. Providing a cross-cutting concern such as authentication is a common theme for engines that fall into this category.
Engines can be used to build components in an SOA, where various service end points can share things like domain models, preventing code duplication. Last year at Rocky Mountain Ruby, Ben Smith gave a good talk on using engines with this approach.
Stand Alone Application
A stand alone application can be rolled up into a Rails engine. This allows you to separate configuration from code, creates distinct extension points, and makes it easy for you and your users to customize the application independently from the main code base. This is the use case I’m covering in this post.
Refactoring as an Engine
Changing a stand alone application to run as an engine takes some work, but the payoff makes it well worth it. I’ll outline the basic approach we used when we were working on the Rearview engine. Taking a similar approach should be enough to get you started in the right direction.
Your setup will consist of two distinct and separate projects: the engine, and the host. Each will have its own directory and repository. The engine will ultimately be a gem you include in your host projects Gemfile. The host will be a full-blown (but mostly bare) rails application. Your users will download your host from git or however you choose to bundle it. The engine then is just a mostly transparent dependency (from the view point of the user.)
The engine will house all your models, views, controllers, helpers, and other logic. The engine will be packaged as a gem and included as a dependency in the host. Start off by creating a new rails engine project:
1 2 3 4 5 6 7 8 9 10 11 12
The validation failure message seen above can be easily corrected by editing the gemspec file,
coyote.gemspec,and replacing the self-explanatory TODO text. Once this is complete you can get started. Soon you’ll be shuffling your code from your original project into the engine. If your an apt git user, you can create a feature branch, remove all your files, and run the command above. As you move forward you would unstage files and refactor them as necessary. You may also just choose to copy files in from your original project.
Copy the gem dependencies from your original projects Gemfile into your engines gemspec. The gemspec file allows for both runtime and development dependencies, but does not provide for gem groups the same way bundler does. At this point your gemspec will look something like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
Note that you’ll still be using bundler to manage these dependencies. Take a look at your projects Gemfile and you’ll see that bundler reads dependencies from your gemspec.
Models in your engine should be copied over from your original project. However, they should be name-spaced now. Models will now go in
app/models/coyote, and each class would be inside the Coyote module. For example:
1 2 3 4
Correspondingly, all tables for your models will be prefixed with coyote. So the table name above would be
coyote_cylinder_head. Before copying all your models, I encourage you to see how files are laid out by running the rails generator:
% bin/rails generate model cylinder_head
Over the lifetime of the application you are converting into an engine, it’s likely you have collected a fair number of migrations. I would recommend rolling these migrations up into one base migration, which is the approach I took with rearview. You can do this be going to your original project and dumping the schema:
% rake db:schema:dump
Then create a new migration in your engine:
% bin/rails generate migration BaseSchema
Copy your schema dump into the change method of the migration. When your engine is included in a host, a rake task is automatically made available that will copy migrations from the engine into the host. The host would then run migrations normally.
In the same way you copied over your models, you will also need to copy over your controllers. They too must be name-spaced. Controllers will be put in
app/controllers/coyote, and each class would also be inside the Coyote module. For example:
1 2 3 4 5 6
Again, you might want to test this out by running a rails generator:
% bin/rails generate resource pistons
Engine Helpers, Views, and the Kitchen-sink
At this point I hope you have gathered enough knowledge to guess how helpers will be laid out:
1 2 3 4
Views should be placed in sub-directories under
app/views/coyote, following the examples above. Views of course are not names-paced with modules.
The rest of your application might be in lib, in
tests/specs, etc. These files will also need to be moved over. It can be a bit tedious to do, but is not as bad as you would think. Make sure all your other classes and modules are also put in the proper namespace.
Once you have the engine setup correctly and your tests passing, your almost there. Create a new rails project that will host your engine:
% rails new coyote-web
During development you can add a gem dependency to your Gemfile that points to your local copy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
Now add a mount point in your hosts
1 2 3
To setup your database in the host (after editing
1 2 3
When you are ready to publish your application, you will need to create a gem from your engine’s gemspec, publish the gem, and then modify your hosts Gemfile dependency.
At the onset there were a few problems we wanted to solve by using engines.
How am I going to separate configuration from code?
In the walk-through above we created two separate projects, an engine and a host. The host is a full rails application independent of the engine. The host only needs to add the engine as a dependency, mount it in the routes, and then run a couple of rake tasks. Take
config/database.yml for example. You can see that your users can choose to use Postgresql, while you may be using mysql. This decision is separate from your engine, because the configuration is in the host.
What about gems that may not be appropriate for some users, such as NewRelic?
You don’t want to impose instrumentation or other features that may be important to you but not appropriate for all your users. Users of your engine can add whatever gems they deem necessary for the application in the hosts Gemfile.
How can I create well-defined extension points for my application?
By using engines your users can override views, extend your models, and add new features in the host. In a follow-up post I’ll provide some examples for how users can extend your engine in these areas.
You can learn more about Rails engines by checking out some of the references I have provided below.
- Unless there’s a good reason not to, isolate your engine
- You might be tempted to start refactoring your code while you re-write it as an engine. Avoid this pitfall. I tried it and found it too distracting and eventually backed out and just focused on porting my application to an engine.
- Make no assumptions about your users environment – be as agnostic as possible
- Provide solid, well documented configuration for your engine
- Strong validation for your configuration will make your users happy and reduce the size of your issues queue on GitHub
This post is cross-posted from Trent Albright’s blog.