Created
September 8, 2013 17:13
-
-
Save yuya-takeyama/6486565 to your computer and use it in GitHub Desktop.
コンストラクタを API として考えると辛い例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# REMOTE_ADDR でアクセス制限を行う Rack Middleware | |
# IP リストがベタ書きになっていて差し替えが難しい | |
class AuthenticationMiddleware | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
if (env['REMOTE_ADDR'].include? ['127.0.0.1']) | |
@app.call(env) | |
else | |
# なんかエラー返す | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# REMOTE_ADDR でアクセス制限を行う Rack Middleware | |
# 許可 IP は何かしらの方法で外から取ってくる | |
# acl_fetcher の差し替えができないのでスタブを使ったテストができない | |
class AuthenticationMiddleware | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
acl_fetcher = AclFetcher.new | |
acl = acl_fatcher.fetch | |
if (env['REMOTE_ADDR'].include? acl) | |
@app.call(env) | |
else | |
# なんかエラー返す | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rack Middleware が例えばこんな API だったら... | |
# ミドルウェアとして Builder とかに渡すのはオブジェクトということにしてしまえば | |
# コンストラクタ引数は好きに変えられるので、依存オブジェクトが増えても対応できる | |
class AuthenticationMiddleware | |
# コンストラクタには依存オブジェクトを渡す | |
def initialize(acl_fetcher) | |
@acl_fetcher = acl_fetcher | |
end | |
# 今までコンストラクタでやってきたことをこっちでやるようにする | |
# こちらは変わりようの無い API という扱い | |
def wrap(app) | |
@app = app | |
end | |
def call(env) | |
acl_fetcher = AclFetcher.new | |
acl = acl_fatcher.fetch | |
if (env['REMOTE_ADDR'].include? acl) | |
@app.call(env) | |
else | |
# なんかエラー返す | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment