1

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.

4
  • Are you not getting all these as params inside an action? Commented Jan 7, 2015 at 11:59
  • No, I know the basic of params but this needs to be done programmatically. Updated the question to clarify that. Commented Jan 7, 2015 at 12:08
  • based on your comment on an answer below? are you looking to run this as a Rack App? Does it need to sit in front of the controller? will it be run in production? Or is it more simulating / gathering metadata about that app? Commented Jan 7, 2015 at 12:51
  • Just gathering metadata. It's primarily needed for a batch controller that lets callers multiplex a bunch of calls together. Commented Jan 7, 2015 at 18:28

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks but I'm looking for an introspection tool where the controller isn't actually run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.