Ruby on Rails中Rack中间件的基础学习教程

2019-09-25 09:36:42于丽

rack会在启动时默认加载一些中间件:

def logging_middleware
    lambda { |server|
     server.server.name =~ /CGI/ || server.options[:quiet] ? nil : [Rack::CommonLogger, $stderr]
    }
   end

    m = Hash.new {|h,k| h[k] = []}
    m["deployment"] = [
     [Rack::ContentLength],
     [Rack::Chunked],
     logging_middleware,
     [Rack::TempfileReaper]
    ]
    m["development"] = [
     [Rack::ContentLength],
     [Rack::Chunked],
     logging_middleware,
     [Rack::ShowExceptions],
     [Rack::Lint],
     [Rack::TempfileReaper]
    ]

    m
   end

包括body长度错误提示访问记录等。

rack有一个Directory的中间件,可以为目录文件生成一个web服务。
使用很简单一句话:

#test.ru
run Rack::Directory.new "~/"
rackup test.ru

这样就会把home目录下的所有文件、文件夹在浏览器中显示

201664170255131.png (1240×371)

rails应用中使用rake middleware即可显示所有的middleware(中间件)

** **rake middleware
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
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
use ActionDispatch::DebugExceptions
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::ParamsParser
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
run Fool::Application.routes

rails使用了rack定义的一些中间件,自定义了一些中间件,其中自定义的routes为rack程序,routes 把rails controller的action变为lambda并作为rack程序运行,在rails 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)>

在config/application.rb可添加、删除、修改中间件

config.middleware.use(new_middleware, args)#:把新中间件添加到列表末尾;
config.middleware.insert_before(existing_middleware,
 new_middleware, args)#:在 existing_middleware

 之前添加新中间件;

config.middleware.insert_after(existing_middleware,
 new_middleware, args)#:在 existing_middleware

 之后添加新中间件;

config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions #替换中间件
config.middleware.delete "Rack::Lock"#删除中间件