Adding a custom middleware to Rails 4

余生颓废 提交于 2019-12-05 00:58:05
  1. Move config/initializers/request_timer.rb to lib/request_timer.rb folder.
  2. Add require_relative '../lib/request_timer' line to application.rb file.
  3. Change config.middleware.use "RequestTimer" to config.middleware.use RequestTimer . Don't use quotes.

I remember that we can't use classes which are at initializers folder without require them at application.rb .

Regards.

And much easier way to solve this is to put your request_timer.rb into app/middleware/request_timer.rb and then added the middleware as a string in your config/application.rb

You should place your middleware class inside the app/middleware folder. The added middleware should be injected in the list of middlewares which are by default added by rails.

Note: You can insert your middleware from anywhere in the code, but its preferred to insert a middleware in any of the initializers which you are adding for your app.

For example, to insert your middleware after rails inbuilt middleware params parser:

Rails.application.middleware.insert_after ActionDispatch::ParamsParser, "RequestTimer"

Additionally, you can also pass required parameters to your middleware something like:

options = { :foo => 'bar' }
Rails.application.middleware.insert_after ActionDispatch::ParamsParser, "SecuredClient", options

Then you can access these parameters in your middleware as follows:

class RequestTimer                                                                                                                                         
  def initialize(app, params)                                                                                                                                      
    @app = app
    @params = params                                                                                          
  end
end

NoMethodError (undefined method 'each' for #<String:0x007fdf649b0028>),you should ensure reponse.body responds to 'each' method, but its class is String.You can fix the code like this: [status, headers, [response.body]]

Ruby 1.9 no longer has each on the String class.

Rack

To use Rack, provide an "app": an object that responds to the call method, taking the environment hash as a parameter, and returning an Array with three elements:
* The HTTP response code
* A Hash of headers
* The response body, which must respond to each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!