Rails で URL に付与されているパラメータ(クエリ)をハッシュに変換する

結論

おそらくこれが一番スマートだと思います。

sample_url = 'https://example.com/?foo=bar&hoge=fuga&this=that&here=there'
query = URI.parse(sample_url).query #=> "foo=bar&hoge=fuga&this=that&here=there"

query_by_hash = Rack::Utils.parse_query(query) #=> {"foo"=>"bar", "hoge"=>"fuga", "this"=>"that", "here"=>"there"}

Capybara で用いる場合

Capybara では現在の URL は current_url で取得できます。したがって、現在のURL のパラメータ(クエリ)をハッシュで取得する場合には以下のように書けます。

query_by_hash = Rack::Utils.parse_query(URI.parse(current_url).query)

注意点

ハッシュのキーはシンボルではなく文字列であることに注意です*1

ドキュメント

www.rubydoc.info

引数を指定することで Cookies の展開にも使えるようです。

*1:Capybara で比較する際など特に

Powered by はてなブログ