A guide to implementing component-based architecture in Rails implemented using:
- Postgresql
- ERB
- Rspec
- Rubocop
Rails Engines are useful for components that use database models and views.
Generating a new engine
Add Rspec and related dependencies
Host application configuration
New engine: ui_core
$ rails plugin new components/ui_core --mountable -dummy-path=spec/dummy -T
Add the following lines to components/ui_core/ui_core.gemspec
spec.add_dependency 'pg'
spec.add_development_dependency 'rspec-rails'
Component test database to use the main app database:
$ cd $RAILS_ROOT/components/ui_core/spec/dummy/config
$ rm database.yml
$ ln –s ../../../../../config/database.yml
Install Rspec:
$ cd $RAILS_ROOT/components/ui_core
$ rails generate rspec:install
Update line of generated rails helper:
From:
require File.expand_path('../../config/environment', __FILE__)
To:
require File.expand_path('../dummy/config/environment', __FILE__)
Add these lines to the main app's Gemfile ($RAILS_ROOT/Gemfile
):
path 'components/' do
gem 'ui_core'
end
Mount the engine by adding these lines to the main app's routes ($RAILS_ROOT/config/routes.rb
):
Rails.application.routes.draw do
mount UiCore::Engine => ‘/’
end
Gems are best for extracting functionality that does not depend on reading/writing to the database and has no view layer
Generating a new gem
Plug into host application
New gem: parser
$ bundle gem parser
Add these lines to the main app's Gemfile ($RAILS_ROOT/Gemfile
):
path 'components/' do
# ...
gem 'parser'
end