Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rack middleware to rails app from gem

I am working on a event handler to report exceptions to a remote api (similar to newrelic agent) and I can not find a way to add my middleware to the rack without doing it in the environment.rb file.

I do not want to do it in the environment.rb file because i plan on turning this into a gem and I would like to minimize the installation process.

Here is the simple middleware I want to add into my app:

#/lib/response_timer.rb
class ResponseTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    #do something here
    @app.call(env)
  end
end

the only way I can find to include it is by adding this to my environment cofig:

config.middleware.use "ResponseTimer"

I have been working with rails for just over a year but this is my first experience with rack and middleware.

Any advice is appreciated!

like image 331
Jessiah Avatar asked Dec 17 '13 09:12

Jessiah


1 Answers

Gems can configure their host apps by providing a Railtie.

For example, here is a shortened version of how the BetterErrors gem does it:

module BetterErrors
  class Railtie < Rails::Railtie
    initializer "better_errors.configure_rails_initialization" do
      Rails.application.middleware.use BetterErrors::Middleware
    end
  end
end
like image 87
janfoeh Avatar answered Oct 12 '22 02:10

janfoeh