Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically add rack middleware with a gem

I have a gem that provides some rack middleware, the only way I can get it to work is to place this in my application.rb

config.middleware.use "TBBC::Editor::Middleware"

How can I make it so that this middleware is automatically used when my gem is used in an apps Gemfile?

like image 773
Arcath Avatar asked Apr 20 '11 11:04

Arcath


1 Answers

If you intend your gem to be used with Rails 3, you could provide a Railtie. You can then automatically load it in case Rails is used.

Assuming your gem's name is tbbc, place this in lib/tbbc/railtie.rb:

module TBBC
  class Railtie < Rails::Railtie
    initializer "tbbc.insert_middleware" do |app|
      app.config.middleware.use "TBBC::Editor::Middleware"
    end
  end
end

In lib/tbbc.rb:

require "tbbc/railtie" if defined? Rails

You can't automatically add the middleware to generic Rack apps. For non-Rails applications, this will be something the user has to do.

like image 177
molf Avatar answered Sep 19 '22 01:09

molf