I am trying to find out how a gem in the Rails 3 gemfile can automatically add middleware to the Rack stack. I am looking for the hook in that gem. For example ... when I add the devise gem to my Rails 3 gemfile, then devise somehow adds warden as middleware on the Rack stack. This seems to work automatically. There is no further configuration needed in the Rails 3 app. I guess there is automatically called a special class/method from boot.rb. Any hints how this process really works?
+1
A:
This won't exactly show how a gem/plugin hooks into middleware, but this is how you can do it. Based on that, a gem/plugin can do the same things:
To insert middleware, you can run this in an initialize file.
ActionController::Dispatcher.middleware.insert_before(ActionController::Base.session_store, FlashSessionCookieMiddleware, ActionController::Base.session_options[:key])
The above will insert a Flash Cookie Middleware (custom code) before the session_store rack is loaded.
To see your own middleware, run rake middleware
use Rack::Lock
use ActionController::Failsafe
use FlashSessionCookieMiddleware, "_xxxxxx_session"
use ActionController::Session::CookieStore, #<Proc:0x00000001037d4f20@(eval):8>
use ActionController::ParamsParser
use Rack::MethodOverride
use Rack::Head
use ActionController::StringCoercion
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
run ActionController::Dispatcher.new
Jesse Wolgamott
2010-07-26 13:05:22
That explains the part of how to add middleware to the Rack stack, thanks. But I still wonder what method/hook of the gem is called by Rails 3, when the gem is just in the Gemfile?
Zardoz
2010-07-26 19:01:52
Ok, I think I solved it. The problem was that I couldn't find the initialize file you mentioned in a gem. In Rails 2.x it was rails/init.rb. But this isn't called in Rails 3 anymore. The way to go is to create a lib/gem_name.rb (where gem_name is the name of that gem). That will be called automatically by Rails 3 when the gem is specified in the Gemfile. And there you can add the middleware. (see https://rails.lighthouseapp.com/projects/8994/tickets/3745-railsinitrb-is-not-being-called-anymore)
Zardoz
2010-07-26 19:46:44
Cool about the Gems! For Rails 2.3 and above (after they moved to rack) -- you create a file named whatever.rb in the directory config/initializers
Jesse Wolgamott
2010-07-26 20:20:42