medihack
medihack

Reputation: 16627

Hook for gems to add middleware on the Rack stack with Rails 3

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?

Upvotes: 4

Views: 4386

Answers (3)

Evil Trout
Evil Trout

Reputation: 9634

You should use a Railtie. In fact, this is the very example given in the Rails::Railtie documentation.

class MyRailtie < Rails::Railtie
  initializer "my_railtie.configure_rails_initialization" do |app|
    app.middleware.use MyRailtie::Middleware
  end
end

Upvotes: 10

David Radcliffe
David Radcliffe

Reputation: 1491

To insert middleware in a gem, you should add it to the gem's engine.

in lib/gem_name/engine.rb

require 'rails'

module GemName
  class Engine < Rails::Engine

    config.app_middleware.insert_before(Warden::Manager, Rack::OpenID)

  end
end

Upvotes: 8

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

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

Upvotes: 3

Related Questions