Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
Zardoz Avatar asked Dec 01 '22 10:12

Zardoz


2 Answers

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
like image 90
Evil Trout Avatar answered Dec 02 '22 22:12

Evil Trout


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
like image 28
David Radcliffe Avatar answered Dec 02 '22 23:12

David Radcliffe