前回,
ミドルウェアとは
ミドルウェアとは何かを一言で言うと,
この仕組みがあることで一体何ができるのでしょうか。Webアプリケーションを作っていると,
ミドルウェアの作りかた
まずは,
- Rackアプリケーションの仕様を満たしていること
- newの第一引数に他のRackアプリケーションを取ること
例えば,
neco_
# coding: utf-8
class NecoFilter
def initialize(app)
@app = app
end
def call(env)
res = @app.call(env)
res[2].each do |body|
body.gsub!(/!|?|。|,/) { "にゃ#{$&}" }
end
res
end
end
そして,
# config: utf-8
require 'simple_app'
require 'neco_filter'
use NecoFilter
run SimpleApp.new
早速rackupでアプリケーションを起動してみましょう。出力が書き換えられているのがわかりますね。前回のSimpleApp同様,
まず,
そして先ほど,
最後にこれは重要なことですが,
もちろんパフォーマンスが何より重要な状況であれば,
余談ですが,
# config: utf-8
require 'simple_app'
require 'neco_filter'
run NecoFilter.new(SimpleApp.new)
useはRack::Builderで用意されたDSLの記法で,
またconfig.
use MiddlewareA
use MiddlewareB
run App.new
となっていたものが,
Rack::Handler::CGI.run MiddlewareA.new( MiddlewareB.new( App.new ) )