Adding a custom middleware to Rails 4
Asked Answered
D

4

20

I have a Rails 4 sample project (Blog) and I have created a simple middleware called 'request_timer' in config/initializers/request_timer.rb

  #config/initializers/request_timer.rb
  class RequestTimer                                                                                                                                         

    def initialize(app)                                                                                                                                      
     @app = app                                                                                                                                              
    end                                                                                                                                                      

    def call(env)                                                                                                                                            
      start_time = Time.now                                                                                                                                  
      status, headers, response = @app.call(env)                                                                                                             
      stop_time = Time.now                                                                                                                                   
      [status, headers, response.body]                                                                                                                       
    end                                                                                                                                                      

  end 

and I have added my middleware in config/application.rb in two ways

1 ) Adding as a constant

#config/application.rb
module Blog                                                                                                                                                  
  class Application < Rails::Application                                                                                                                     
    config.middleware.use RequestTimer                                                                                                                       
  end                                                                                                                                                        
end

this way when I try to run my rails app I'm getting the error

/Users/sameera/workspace/ruby-rack/blog/config/application.rb:9:in `require': cannot load such file -- request_timer (LoadError)
    from /Users/sameera/workspace/ruby-rack/blog/config/application.rb:9:in `<top (required)>'
    from /Users/sameera/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands.rb:74:in `require'
    from /Users/sameera/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands.rb:74:in `block in <top (required)>'
    from /Users/sameera/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands.rb:71:in `tap'
    from /Users/sameera/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands.rb:71:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

2 ) Then I added my middleware as a string

#config/application.rb
module Blog                                                                                                                                                  
  class Application < Rails::Application                                                                                                                     
    config.middleware.use "RequestTimer"                                                                                                                       
  end                                                                                                                                                        
end

This ways, it allows me to run the rails server, but when I access localhost:3000, it errors saying

NoMethodError (undefined method `each' for #<String:0x007fdf649b0028>):
  rack (1.5.2) lib/rack/etag.rb:58:in `digest_body'
  rack (1.5.2) lib/rack/etag.rb:26:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/flash.rb:241:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/cookies.rb:486:in `call'
  activerecord (4.0.2) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
  activerecord (4.0.2) lib/active_record/migration.rb:369:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.2) lib/active_support/callbacks.rb:373:in `_run__2755475928771109453__call__callbacks'
  activesupport (4.0.2) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.2) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.2) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.2) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.2) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.0.2) lib/rails/engine.rb:511:in `call'
  railties (4.0.2) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/sameera/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
  /Users/sameera/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
  /Users/sameera/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

What would be the reason? I'm using Rails 4.0.2 and rack-1.5.2 and ruby 2.0.0p247.

Diecious answered 22/1, 2014 at 21:3 Comment(0)
A
36
  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.

Albert answered 9/6, 2014 at 14:28 Comment(2)
Depends on Rails version I think. For Rails 3.x I used def call(env) @app.call env endBevan
This is the absolute correct answer for Rails 5+. Here's the relevant discussion with Rails core: github.com/rails/rails/issues/25525#issuecomment-479941866Emmettemmey
I
5

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

Interlineate answered 23/2, 2016 at 4:26 Comment(4)
@memoht why are you downvoting my answer? it is deprecated, but in rails 5. The question is about rails 4!Interlineate
You are correct. I removed my comment and will remove the down vote if SO lets me.Baileybailie
Adding to the answer the fact that this is deprecated in Rails 5 would be useful.Finalism
Note, in Rails 5+ you can no longer use the String for the name of the middleware. You need to use the proper class name. Additionally, according to @rafaelfranca (Rails core), "middleware can't be in app because they can't be reloaded. They should be in lib and if you put them in lib, require_relative will work." github.com/rails/rails/issues/25525#issuecomment-479941866Emmettemmey
H
2

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
Hewart answered 23/6, 2016 at 17:7 Comment(1)
Note, in Rails 5+ you can no longer use the String for the name of the middleware. You need to use the proper class name. Additionally, according to @rafaelfranca (Rails core), "middleware can't be in app because they can't be reloaded. They should be in lib and if you put them in lib, require_relative will work." github.com/rails/rails/issues/25525#issuecomment-479941866Emmettemmey
O
1

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

Orpiment answered 21/4, 2015 at 5:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.