Sunday, August 28, 2016

How I create my Rails Engines

Akin to my previous post, How I create my Rails projects, here's how I personally create my Rails Engines.

Project Creation


After making sure I have the correct version of Rails installed (see previous post), I run:

rails plugin new <name> --dummy_path=spec/dummy --skip-test-unit --mountable

As with Rails projects, I favor Rspec over Test Unit, so I remove the latter from my engine.

I mostly prefer engines that run in isolation, so --mountable suits my needs better than --full here.

Rspec Setup


I do the following changes:

Add to gemspec file:
s.test_files = Dir["spec/**/*"]
s.add_development_dependency 'rspec-rails'
If I am working with database, I also add SQLite3 as it is portable and suitable for isolated testing:
s.add_development_dependency 'sqlite3'
Afterwards I run bundle install to install dependencies.

Engine Setup


I add to lib/engine.rb, inside the class definition:

isolate_namespace <MyEngineName>

config.generators do |g|
  g.assets false # if I'm not using assets
  g.helper false
  g.test_framework :rspec
  g.fixture_replacement :factory_girl, :dir => 'spec/factories' # if I'm using FactoryGirl
end

If I'm using migrations, I keep them inside my Engine instead of having them copied to the host application:

initializer :append_migrations do |app|
  unless app.root.to_s.match root.to_s
    config.paths["db/migrate"].expanded.each do |expanded_path|
      app.config.paths["db/migrate"] << expanded_path
    end
  end
end

Then, to create a model inside my Engine, I use bin/rails from the application root:

bin/rails generate model <nome>

And to run the migration for manual testing:

rake app:db:migrate

Then, the dummy app can be manually started with:

cd spec/dummy
rails s # or rails c for console

Testing


After I build some code and tests, I prepare the database and run the tests with:

rake app:db:test:prepare
rspec