4.1 Rack
Rack is a modular interface for handling web requests, written in Ruby, with support for many different webservers. It abstracts away the handling of HTTP requests and responses into a single, simple call method thatcan be used by anything from a plain Ruby script all the way to Rails itself.
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello world!"]]
end
end
An HTTP request invokes the call method and passes in a hash of environment variables, akin to the way that CGI works. The call method should return a 3-element array consisting of the status, a hash of response headers, and finally, the body of the request.
Want to see which Rack filters are enabled for your Rails 4 application? There’s arake task for that!
> rake middleware
4.1.1 Configuring Your Middleware Stack
Your application object allows you to access and manipulate the Rack middleware stack during initialization,via config.middleware
like:
#application.rb
module Example
class Application < Rails::Application
...
# Rack::ShowStatus catches all empty responses the app it wraps and # replaces them with a site explaining the error.
config.middleware.use Rack::ShowStatus
end
end
The methods of config.middleware
give you very fine-grained control over the order in which your middleware stack is configured. The args parameter is an optional hash of attributes to pass to the initializer method of your Rack filter.
4.1.1.1 config.middleware.insert_after(existing_middleware, new_middleware, args)
Adds the new middleware after the specified existing middleware in the middleware stack.
4.1.1.2 config.middleware.insert_before(existing_middleware, new_middleware, args)
Adds the new middleware before the specified existing middleware in the middleware stack.
4.1.1.3 config.middleware.delete(middleware)
Removes a specified middleware from the stack.
4.1.1.4 config.middleware.swap(existing_middleware, new_middleware, args)
Swaps a specified middleware from the stack with a new class.
4.1.1.5 config.middleware.use(new_middleware, args)
Takes a class reference as its parameter and just adds the desired middleware to the end of the middleware
stack.
网友评论