Basic Learning tutorials on rack middleware in Ruby on Rails _ruby topics

Source: Internet
Author: User
Tags hash prepare sendfile ruby on rails

Rack is a framework between the Ruby server and the rack application, Rails,sinatra is built on rack and belongs to the rack application.

Rack provides a standard interface for interacting with the server. The standard rack program is an object that responds to call, can be an object, a Proc, a lambda, or even method, which receives the env parameter (the Environment object) and returns an array that includes:

    • State (status), HTTP response status code
    • Can be hash, header information for HTTP
    • The object that owns each method, and each returns a string

Rack is extended through middleware, which is to decorate the original rack program, to further process it on the basis of the original return array, and to return the rack object

A simple rack program

Require ' rack '

app = lambda{|env|[ 200,{},["Hello from Rack"]]} app

Rack programs using the middleware:
Require ' rack '

Class Decorator
 def initialize (app)
  @app = App
 def call (env)
  status, headers, BODY = @app. Call ( ENV)
  new_body = "from middleware input <br/>"
  body.each{|str| new_body << str}
  headers[' Content-length '] = new_body.bytesize.to_s
  [Status, headers, [new_body]]

app = lambda{|env | [200,{},["Hello from Rack"]]} (APP)

The above method of using middleware is easily confusing when using multiple, rack has a builder class can effectively manage
Use the following
Require ' rack '

Require ' decorator '

app ={use
 rack::contentlength use
 Run Lambda {| env| [MB, {"Content-type" => "text/html"}, ["Hello World"]}
}. To_app App

Using the Rack::builder map method, you can create a routed rack program
Require ' rack '

App = {
 map '/hello ' do
run lambda {|env| [MB, {"Content-type" => "text/html"}, ["Hello"]]} End
map '/world ' do
run lambda {|env| [MB, {"Content-type" => "text/html"}, ["World"]]}
Map '/' do
run lambda {|env| [MB, {"Content-type" => "text/html"}, ["All"]]} End
}.to_app app,:P ORT => 3000

Because of the full stack of rails, there are many rack middleware that are used in some highly concurrent but business-simple Web sites or APIs
The response time is too long, in which case you may consider using rack or Sinatra.

There are two ways to start a rack program:

1. Run the. rb file directly using Ruby, default start service in 8080, no log file
2. Using Rackup, the default is to start the service in 9292, there are log files, Rackup can use-o specified IP,-p to specify the port number

Require ' rack '
app = lambda{|env| [200,{},["Hello World"]} app
Ruby xxx.rb

#test. Ru
Run lambda{|env| [200,{},[' rackup start]]}

Rack will load some middleware by default at startup:

def logging_middleware
    Lambda {|server| =~/cgi/| | Server.options[:quiet]? Nil: [Rack::commonlogger, $stderr]

    m = {|h,k| H[k] = []}
    m[' deployment '] = [
     [Rack: : ContentLength],
    m[" Development "] = [
     [Rack:: Showexceptions],


Include the body length error prompt access record, and so on.

Rack has a directory middleware that can generate a Web service for catalog files.
Use a simple word:

#test. Ru
Run Rack::D "~/"

This will display all the files and folders in the home directory in the browser

Use rake middleware in rails applications to display all middleware (middleware)

* * **rake middleware use
rack::sendfile with
actiondispatch::static use
activesupport::cache::strategy::localcache::middleware:0x007feef1563b90> use
Rack::Runtime use
Rack:: Methodoverride use
actiondispatch::requestid use
rails::rack::logger use
actiondispatch:: Showexceptions use
webconsole::middleware with
actiondispatch::D ebugexceptions use
actiondispatch:: Remoteip use
actiondispatch::reloader use
actiondispatch::callbacks use
activerecord::migration:: checkpending use
activerecord::connectionadapters::connectionmanagement use
activerecord::querycache Use
actiondispatch::cookies use
actiondispatch::session::cookiestore use
actiondispatch::flash Use
actiondispatch::P aramsparser use
rack::head use rack::conditionalget use
Run Fool::application.routes

Rails uses some middleware defined by rack, customizing some middleware, where the custom routes is a rack program, routes turns the rails controller action into a lambda and runs as a rack program, in Rails Input in console

2.2.1:001 > Questionscontroller.action (: New)
 => #<proc:0x007fbe482ee0b0@/users/killman/.rvm/gems/ ruby-2.2.1/gems/actionpack-4.2.1/lib/action_controller/metal.rb:237 (lambda) >

To add, remove, and modify middleware in CONFIG/APPLICATION.RB

Config.middleware.use (New_middleware, args) #: Add new middleware to the end of the list;
Config.middleware.insert_before (existing_ Middleware,
 new_middleware, args) #: in Existing_middleware

Add new middleware before;

Config.middleware.insert_after (Existing_middleware,
 new_middleware, args) #: in Existing_middleware

then add new middleware;

Config.middleware.swap actiondispatch::showexceptions, lifo::showexceptions #替换中间件
config.middleware.delete " Rack::lock "#删除中间件

The role of middleware:

  • Rack::sendfile: Sets the X-sendfile header on the server. Set through the Config.action_dispatch.x_sendfile_header option.
  • Actiondispatch::static: Used to service static resource files. If the option Config.serve_static_assets is false, this middleware is disabled.
  • Rack::lock: Set the env["Rack.multithread" flag to False, the program into the mutex.
  • Activesupport::cache::strategy::localcache::middleware: Save cache in memory, not thread safe.
  • Rack::runtime: Sets the X-runtime header, which is the length of time to execute the request, in seconds.
  • Rack::methodoverride: If the Params[:_method] parameter is specified, the requested method used is overwritten. This middleware implements the put and DELETE methods.
  • Actiondispatch::requestid: Sets a unique X-request-id header in the response and enables the Actiondispatch::request#uuid method.
  • Rails::rack::logger: Reminder log at the start of request, written to log after request completes.
  • Actiondispatch::showexceptions: All exceptions thrown by the remedy, calling the program that handles the exception, and displaying it to the user in a specific format.
  • Actiondispatch::D ebugexceptions: If developed locally, write the exception to the log and display a debug page.
  • ACTIONDISPATCH::REMOTEIP: Check the IP of the spoofing attack.
  • Actiondispatch::reloader: Provides "prepare" and "clean" callbacks to assist in the code reload feature in the development environment.
  • Actiondispatch::callbacks: Invokes a "prepare" callback before processing the request.
  • Activerecord::migration::checkpending: Check whether the migration is pending, and if so, throw ActiveRecord::P endingmigrationerror exception.
  • Activerecord::connectionadapters::connectionmanagement: After the request processing is complete, clean the active connection unless you set the Rack.test to true in the environment in which the request originated.
  • Activerecord::querycache: Enable Active record query caching.
  • Actiondispatch::cookies: Set the requested Cookies.
  • Actiondispatch::session::cookiestore: In charge of storing conversations in cookies.
  • Actiondispatch::flash: Sets the key for the Flash message. Available only if the Config.action_controller.session_store option is set.
  • Actiondispatch::P aramsparser: To params the parameters in the request.
  • Actiondispatch::head: Converts the head request into a GET request and processes it.
  • Rack::conditionalget: Adds support for conditional get, and does not respond if the page has not been modified.
  • Rack::etag: Adds a ETags header to the body of all string types. ETags is used to validate caching.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.