How to add rack middleware to rails app from gem
Asked Answered
E

2

5

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!

Electrometallurgy answered 17/12, 2013 at 9:17 Comment(0)
N
17

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
Nightingale answered 17/12, 2013 at 10:13 Comment(1)
Thank you this was exactly the answer I was looking for!Electrometallurgy
G
-6

http://rubylearning.com/blog/a-quick-introduction-to-rack/

for the basic tutorial of rack a clear explanation may solve your problem

Gillan answered 17/12, 2013 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.