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 -TAdd 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.ymlInstall Rspec:
$ cd $RAILS_ROOT/components/ui_core
$ rails generate rspec:installUpdate 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'
endMount 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 => ‘/’
endGems 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 parserAdd these lines to the main app's Gemfile ($RAILS_ROOT/Gemfile):
path 'components/' do
# ...
gem 'parser'
end