-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Use devise inside a mountable engine
Installing Devise in a mountable engine is nearly identical to installing Devise in an application. However, there are a few additional configuration options that need to be adjusted.
Installing Devise in an engine follows the same steps as the general installation instructions, but we'll be running the commands from our engine's directory and benefiting from the namespaced rails
helper there.
Add Devise to the engine's dependencies in your gemspec:
Gem::Specification.new do |s|
s.add_dependency "devise"
end
Generate the config files:
rails generate devise:install
And generate a model if you need to:
rails generate devise MODEL
You'll need to direct Devise to use your engine's router. To do this, set Devise.router_name
in config/initializers/devise.rb
. It should be a symbol containing the name of the mountable engine's named-route set. For example, if your engine is namespaced as MyEngine
:
Devise.setup do |config|
config.router_name = :my_engine
end
Your user class is probably namespaced, so you'll need to pass that to the Devise helper in routes.rb
:
MyEngine::Engine.routes.draw do
devise_for :users, class_name: "MyEngine::User"
end
If your engine uses isolate_namespace
, Devise will assume that all of its controllers reside in your engine rather than Devise. To correct this, add :module => :devise
to the routes helper:
MyEngine::Engine.routes.draw do
devise_for :users, class_name: "MyEngine::User", module: :devise
end
You probably want Devise's controllers to inherit from your engine's controller and not the main controller. Set this in config/initializers/devise.rb
:
Devise.setup do |config|
config.parent_controller = 'MyEngine::ApplicationController'
end
Finally, you'll need to require Devise in your engine. Add the following line to lib/my_engine.rb
:
require 'devise'
NOTE: If you need to override the standard devise views (i.e. app/views/devise/sessions/new) you will want to require 'devise' before you require your engine. This way the view order will get configured appropriately and you can manage the overrides within your engine rather than the main app.
http://github.com/BrucePerens/perens-instant-user/ is an example Rails Engine that adds Devise to the application while keeping most of the complexity of using Devise in the engine rather than your application.
It contains pre-defined mountable routes for Devise, and a pre-defined User model. Its installation steps are easier than those of stand-alone Devise. Unlike stand-alone Devise, you aren't advised to become a Ruby Wizard before installing it :-)