背景 _pathヘルパーで疑問が発生しました。qというクエリパラメータがnilだった場合、?q=となるのか、クエリパラメータなしになるのかが気になりました。
わざわざローカルでrails serverをせず確認する方法はないのかな?と思ってググってみました。
rails consoleでpathヘルパーの実験 appというオブジェクトを利用すると呼び出せるよと書かれていたので、早速試してみます
1 2 3 4 5 6 7 $ rails c [1] pry(main)> app.login_path => "/login" [2] pry(main)> app.login_path q: nil => "/login" [3] pry(main)> app.login_path q: 'abc' => "/login?q=abc"
ということで、クエリパラメータの値がnilの場合はクエリパラメータなしになるようでした。
最初に思った?q=になる場合は、q: ''でした。
appというオブジェクトはなにか? appというオブジェクトはなにでしょうか?試してみます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 [1] pry(main)> app.class => ActionDispatch::Integration::Session [2] pry(main)> ActionDispatch::Integration::Session.ancestors => [ActionDispatch::Integration::Session, ActionDispatch::Routing::UrlFor, ActionDispatch::Routing::PolymorphicRoutes, ActionController::ModelNaming, ActionDispatch::TestProcess, ActionDispatch::Integration::RequestHelpers, ActionDispatch::Assertions, ActionDispatch::Assertions::RoutingAssertions, ActionDispatch::Assertions::ResponseAssertions, Rails::Dom::Testing::Assertions, Rails::Dom::Testing::Assertions::TagAssertions, Rails::Dom::Testing::Assertions::SelectorAssertions, Rails::Dom::Testing::Assertions::SelectorAssertions::CountDescribable, Rails::Dom::Testing::Assertions::DomAssertions, Minitest::Assertions, Object, PP::ObjectMixin, Delayed::MessageSending, V8::Conversion::Object, ActiveSupport::Dependencies::Loadable, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject]
ancestorsのところは、バージョンによって異なるかもしれません。
これだけみてもわからないので、他の利用方法も見てみます。
app.getでリクエストを送る app.getにパスを引数で渡すと、実際にリクエストを送ることができます
1 2 3 4 5 6 7 [1] pry(main)> app.get '/login' Started GET "/login" for 127.0.0.1 at 2020-12-02 23:24:26 +0900 ActiveRecord::SchemaMigration Load (2.0ms) SELECT `schema_migrations`.* FROM `schema_migrations` Processing by Users::SessionsController#new as HTML (省略) Completed 200 OK in 7125ms (Views: 7095.9ms | ActiveRecord: 11.5ms) => 200
なるほど、便利ですね!
ドキュメント にあるように、request、response、controllerなどのメソッドもあり、最後のリクエストのそれぞれが取得できるようです。
まとめ Railsは長い間使ってきましたが、まだまだ知らないことがいっぱいありそうです。
これからもなにか見つけたら紹介していきたいと思います。