Ruby程序员

Ruby进阶之Rack入门

2016-12-27  本文已影响784人  感觉被掏空

简介

基本上所有的 Ruby web framework 都是Rack App,web框架大多都是基于rack之上的,比如Ruby On Rails、Sinatra.......,Rack帮助我们封装处理了很多基本的操作,并提供了大量工具

Rack

安装 gem

gem install rack

如何使用

简单尝试

#! /usr/bin/env ruby
#  encoding: utf-8

require 'rack'

app = proc { |env| [200, {}, ['hello world']] }

::Rack::Handler::WEBrick.run app
分析

env对象

#! /usr/bin/env ruby
#  encoding: utf-8

require 'rack'

class MyApp
  def call(env)
    puts env.inspect
    [200, {'Content-Type' => 'text/plain'}, ['hello world']]
  end
end

::Rack::Handler::WEBrick.run MyApp.new

Rack中间件介绍

Rack中间件简单使用

新建一个文件 config.ru

#! /usr/bin/env ruby
#  encoding: utf-8

require 'rack'

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    code, headers, body = @app.call(env)
    body << ['this is my middleware']
    [code, headers, body]
  end
end

class MyApp
  def call(env)
    [200, {'Content-Type' => 'text/plain'}, ['hello world']]
  end
end

use MyMiddleware
run MyApp.new

Rack提供的路由

#! /usr/bin/env ruby
#  encoding: utf-8

require 'rack'

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    code, headers, body = @app.call(env)
    body << 'this is my middleware'
    [code, headers, body]
  end
end

class MyApp
  def call(env)
    [200, {'Content-Type' => 'text/plain'}, ['hello world']]
  end
end

app = Rack::Builder.app do 
  map '/' do
    run MyApp.new
  end
  map '/middleware' do
    use MyMiddleware
    run MyApp.new
  end
end

run app

总结

后面我们会深入Rack更多知识

上一篇 下一篇

猜你喜欢

热点阅读