rack知识 rails on rack

一、什么是Rack?

          rack 实际上是一种api,也是一种标准。它用最简单的方式封装了http请求和响应,是统一和提炼了服务器和框架,以及两者之间的软件(中间件)的api(接口)和作为他们链接的一种标准。rack所形成的中间件可以拦截http的request同时可以改变response,相当于向应用程序请求。所以中间件当起的角色更像是filter。

二、rack的作用:

  • Rack的框架roll你的ruby框架
  • Rack提供了你的不同的web server 和框架/应用的交互,这样可以让框架可以兼容更多的web server(必须得支持Rack),如:Phusion Passenger, Litespeed, Mongrel, Thin, Ebb, Webrick
  • Rack可以减少应用程序的开支,可以很自由的获取request,respond session cookies 和params
  • Rack还可以让一个程序可以包含多个框架,没有class的冲突,Rails和sinatra的整合是最好的例子
  • Rack生成的中间件可以重复使用于不同的框架/应用,比如:同一个Anti-spamming rack middleware可以使用在你的rails app,sinatra app 或者的your custom Rack application

三、rack 的规定:

      返回一个返回参数(enviroment)的call()函数;

      call()函数return一个数组[http_status_code, responde_header_hash, body]

四、rack的实例解析:

  1、

require 'rubygems'
require 'rack'

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

Rack::Handler::Mongrel.run HelloWorld.new, :Port => 9292
通过传递HelloWorld的一个对象到mongrel rack handler ,然后启动了服务端口9292
2、
require 'rubygems'
require 'rack'

Rack::Handler::Mongrel.run proc {|env| [200, {"Content-Type" => "text/html"}, "Hello Rack!"]}, :Port => 9292
应为返回的是一个call()函数,可以用proc来实现代码
3、
require 'rubygems'require 'rack'

def application(env)
  [200, {"Content-Type" => "text/html"}, "Hello Rack!"]
end
Rack::Handler::Mongrel.run method(:application), :Port => 9292
使用方法类来实现

五、安装了rack gem
还可以这样实现上面的代码:
在config.ru
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, "Hello Rack!"]}
然后运行:
rackup config.ru
六、实现添加Rack中间件例子(rails 3):
# in config/application.rb
     config.middleware.use '类名'

# in config/initializers/文件名.rb
class ResponseTimer
  def initialize(app, message = "Response Time")
    @app = app
    @message = message
  end
  
  def call(env)
    dup._call(env)
  end
  
  def _call(env)
    @start = Time.now
    @status, @headers, @response = @app.call(env)
    @stop = Time.now
    [@status, @headers, self]
  end
  
  def each(&block)
    block.call("<!-- #{@message}: #{@stop - @start} -->
") if @headers["Content-Type"].include? "text/html"
    @response.each(&block)
  end
end
打开网页的源代码。
更对关于rack资源链接:
http://asciicasts.com/episodes/151-rack-middleware
https://github.com/JuanitoFatas/Guides/blob/master/guides/edge-translation/rails-on-rack-zh_CN.md#41-%E5%AD%A6%E4%B9%A0-rack
https://github.com/ruby-china/rails-guides/blob/master/source/CN/rails_on_rack.textile
http://www.cnblogs.com/lidaobing/archive/2010/10/19/1855958.html
http://kqis.me/ruby/2013/09/26/rack/
https://ruby-china.org/topics/15017


 
 
 
原文地址:https://www.cnblogs.com/chenzhenzhen/p/4017726.html