2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RackアプリケーションのエンドポイントをHTTPを経由せずに呼び出す方法

Posted at

概要

たとえば Sinatra でとあるエンドポイントから他のエンドポイントから呼び出したくなったこと、ありませんか?

require "sinatra/base"
class WebApp < Sinatra::Base
  get "/" do
    # ここで /callee を実行して、その返り値を得たい
    # でもHTTPリクエスト経由にはしたくない
  end

  get "/callee" do
    "From /callee data"
  end
end
run WebApp

論よりコード

require "sinatra/base"
class WebApp < Sinatra::Base
  get "/" do
    status, headers, content = WebApp.call(Rack::MockRequest.env_for("/callee"))
    "I am '/' #{content.first}"
  end

  get "/callee" do
    "From /callee data"
  end
end
run WebApp
$ curl localhost:9292/
I am / From /callee data

解説

Rack::MockRequestを使ってリクエストを行ったように見せる方法です
rack/test で使われている方法を参考にしました

Sinatraに限らず、RailsやGrapeでも使うことができます

注意: contentのデータ構造はフレームワークによってマチマチなので、適当に合わせてください (e.g. Grapeは content.body が実データ(Array)になります)

あとがき

そもそも、こうならないように設計すべきですけど
これじゃテストもやりにくいし

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?