What is Rack::Builder ?
Rack::Builder是一种很小的,用来构件Rack应用程序的DSL语言
Rack::Builder将Rack middlewares和applications结合起来,转换成一个真正的rack application,可以把Rack::Builder比作是栈,底层是你的rack application,中间件在其上,而整个栈本身也是一个rack application。
切换到rails工程目录下,执行rack config.ru会在工程的根目录下生成一个config.ru的文件,修改文件内容如下
require ::File.expand_path('../config/environment', __FILE__) run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["Hello Rack!"]]}
重新启动服务器,rack config.ru,打开 http://localhost:9292 页面显示为 Hello,Rack!
Rack::Builder 的三个重要的实例方法
infinity = Proc.new {|env| [200, {"Content-Type" => "text/html"}, [env.inspect]]} builder = Rack::Builder.new builder.run infinity Rack::Handler::WEBrick.run builder, :Port => 9292
Rack::Bulder#initialize同样支持代码块
infinity = Proc.new {|env| [200, {"Content-Type" => "text/html"}, [env.inspect]]} builder = Rack::Builder.new do run infinity end Rack::Handler::WEBrick.run builder, :Port => 9292
Rack::Bulder#use将中间价加入到rack application中,rack 有很多有用的中间件,其中之一有Rack::CommonLogger
infinity = Proc.new {|env| [200, {"Content-Type" => "text/html"}, [env.inspect]]} builder = Rack::Builder.new do use Rack::CommonLogger run infinity end Rack::Handler::WEBrick.run builder, :Port => 9292
Rack::Bulder#map 类似于rails中routes中的map,用来做路由
infinity = Proc.new {|env| [200, {"Content-Type" => "text/html"}, [env.inspect]]} builder = Rack::Builder.new do use Rack::CommonLogger map '/' do run infinity end map '/version' do run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["infinity 0.1"]] } end end Rack::Handler::WEBrick.run builder, :Port => 9292
需要注意的是:当访问的url于version匹配上,则显示infinity 0.1,
比如: http://localhost:9292/version, http://localhost:9292/version/xxx
如果没有匹配上,则显示系统信息 ,比如
http://localhost:9292/, http://localhost:9292/versiontest, http://localhost:9292/xxx
同样支持嵌套的格式,如下
require ::File.expand_path('../config/environment', __FILE__) infinity = Proc.new {|env| [200, {"Content-Type" => "text/html"}, [env.inspect]]} builder = Rack::Builder.new do use Rack::CommonLogger map '/' do run infinity end map '/version' do map '/' do run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["infinity 0.1"]] } end map '/last' do run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["infinity beta 0.0"]] } end end end Rack::Handler::WEBrick.run builder, :Port => 9292
http://localhost:9292/version/last 返回:infinity beta 0.0
http://localhost:9292/version/lastxx 返回:infinity 0.1
http://localhost:9292/,http://localhost:9292/xxx 返回:系统信息
原文资料:http://m.onkey.org/ruby-on-rack-2-the-builder