Reputation: 46369
I need to programmatically extract the params from a URL, ie the hash that the controller would receive if the URL was called. This is not happening inside the controller, it's for an introspection tool, so the controller is never run. I want to predict what would happen if the controller was run, hopefully using the same API Rails itself is using.
For example, given a Rails route /blogs/:id
and a URL query of /blogs/123?published=true
, I want to extract { id: 123, published: true }
.
Using Rails.application.routes.recognize_path
, I can get the id
in this example as it's part of the route pattern, but not the extra CGI param (published
). I could manually add those, but I'd like to know if there's a proper API for this.
Upvotes: 1
Views: 1536
Reputation: 4538
You can parse the URL, read the query string and convert them to hash.
u = URI.parse("http://localhost:3000/blogs/213?published=true")
cgi_params = u.query.split('&').map { |e| e.split('=') }.to_h
Merge them with params
that you got using Rails.application.routes.recognize_path
Upvotes: 3
Reputation: 176342
The params
Hash contains all the route parameters, including the query parameters.
# Given /blogs/123?published=true
def action
params[:id] # => 123
params[:published] # => "true"
end
Upvotes: 1