Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add middleware in Rails 4.2 application

I am trying to learn Middlewares and been practising how to mount it in the Rails application. I have followed the railscast

So far I have implemented these steps:

1) Created a new Rails 4.2 application called: Blog

2) Added a file in the lib folder named as response_timer.rb.

class ResponseTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    [200, {"Content-Type" => "text/html"}, "Hello World"]
  end
end

3) Added config.middleware.use "ResponseTimer" in application.rb.

config.middleware.use "ResponseTimer"

But as i'm hitting the command rake middleware in the terminal, it is reporting this error:

rake aborted!
NameError: uninitialized constant ResponseTimer

I tried also to add the config.middleware.use "ResponseTimer" in the development.rb but again facing the same error.

What am i missing here?

Please help.

Referenced article: http://guides.rubyonrails.org/rails_on_rack.html

like image 723
Hashmita Raut Avatar asked Oct 19 '22 17:10

Hashmita Raut


1 Answers

Middleware has to have an accompanying module / class, and needs to be loaded in the app before it can be referenced. The way to do this in Rails is with autoloading (lib files aren't autoloaded by default):

#config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.middleware.use "ResponseTimer"

The above should work for you.

like image 91
Richard Peck Avatar answered Oct 31 '22 22:10

Richard Peck