rails - 新增middleware

栏目: Ruby · 发布时间: 7年前

内容简介:sinatra 与 rails 的重大区别,就可以认为 后者有茫茫多的middleware.我们平时用的不多,但是关键时刻需要知道这个,需要读懂代码.下面就是一个简单的middleware 的使用过程. 具体参考:

sinatra 与 rails 的重大区别,就可以认为 后者有茫茫多的middleware.

我们平时用的不多,但是关键时刻需要知道这个,需要读懂代码.

下面就是一个简单的middleware 的使用过程. 具体参考: http://railscasts.com/episodes/151-rack-middleware?autoplay=true

1. 新建rails项目

2. 新建一个 middleware . (放到lib 目录下也行, 放到哪里都行)

class MyMiddleware

  # app is the rails app
  def initialize app 
    @app = app 
  end 

  # env: request env
  def call env 
    request_started_on = Time.now
    @status, @headers, @response = @app.call(env)
    request_ended_on = Time.now

    Rails.logger.debug "=" * 50
    Rails.logger.debug "Request delta time: #{request_ended_on - request_started_on} seconds."
    Rails.logger.debug "=" * 50

    [@status, @headers, @response]
  end 
end

3. 在 config/application.rb 中,添加:

config.middleware.use "MyMiddleware"

4. 查看是否加载:$ bundle exec rake middleware , 就可以看到我们的middleware已经放上去了.

5. 运行rails, 打开任意一个页面,都可以看到有logger  出来,如下:

Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2018-07-10 17:27:22 +0800
==================================================
Request delta time: 0.002136335 seconds.
==================================================

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具