Rails engine
In Ruby on Rails, a Rails engine is a self-contained and modular application that can be mounted within a larger Rails application. Engines can be thought of as “miniature applications” that can be used to modularize and reuse code across multiple Rails applications. Engines can include models, controllers, views, assets, and routes that are isolated from the main application but can be easily integrated when mounted. By using Rails engines, developers can create and distribute reusable functionality that can be shared across multiple Rails applications.
Here is a step-by-step tutorial for creating a Rails engine:
- Create a new Rails application:
rails new my_engine --mountable
The --mountable
the flag tells Rails to create a mountable engine.
2. Create a new controller in your engine:
rails g controller MyEngine::Welcome index
3. Add a route to your engine’s config/routes.rb
file:
MyEngine::Engine.routes.draw do root to: 'welcome#index' end
4. Create a layout file in app/views/layouts/my_engine/application.html.erb
.
5. Create a view file in app/views/my_engine/welcome/index.html.erb
.
6. Test your engine by running the Rails server:
rails s
Then visit http://localhost:3000/my_engine
in your browser.
7. Create a gemspec file:
bundle gem my_engine
8. Add your engine to the gemspec file in my_engine.gemspec
:
s.name = ‘my_engine’
s.version = ‘0.1.0’
s.summary = ‘A brief description of my engine’
s.description = ‘A longer description of my engine’
s.authors = [‘Your Name’]
s.email = ‘you@example.com’
s.files = Dir[‘{app,config,db,lib}/**/*’, ‘MIT-LICENSE’, ‘Rakefile’, ‘README.md’]
s.test_files = Dir[‘test/**/*’]
s.require_paths = [‘lib’]
s.add_dependency ‘rails’, ‘>= 6.1.0’
9. Build your gem:
gem build my_engine.gemspec
10. Install your gem locally:
gem install ./my_engine-0.1.0.gem
11. Create a new Rails application to test your gem:
rails new my_engine_test
12. Add your gem to the Gemfile
:
gem 'my_engine', path: '../my_engine'
13. Mount your engine in the test application’s config/routes.rb
file:
Rails.application.routes.draw do
mount MyEngine::Engine => ‘/my_engine’
end
14. Test your engine by running the Rails server:
rails s
Then visit http://localhost:3000/my_engine
in your browser.
That’s it! You now have a working Rails engine.