mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Parse Query Params From A URL as a rails til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_1039 TILs and counting..._
|
||||
_1040 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -661,6 +661,7 @@ _1039 TILs and counting..._
|
||||
- [Migrating Up Down Up](rails/migrating-up-down-up.md)
|
||||
- [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md)
|
||||
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
|
||||
- [Parse Query Params From A URL](rails/parse-query-params-from-a-url.md)
|
||||
- [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md)
|
||||
- [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md)
|
||||
- [Pretend Generations](rails/pretend-generations.md)
|
||||
|
||||
59
rails/parse-query-params-from-a-url.md
Normal file
59
rails/parse-query-params-from-a-url.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Parse Query Params From A URL
|
||||
|
||||
For all of the conveniences that Ruby and Rails affords a developer through
|
||||
their expansive APIs, I am always surprised that it is hard to inspect the
|
||||
query params in a URL.
|
||||
|
||||
Let's take a URL and walk through the steps it takes to pull out the value of a
|
||||
query param.
|
||||
|
||||
Here's a URL:
|
||||
|
||||
```ruby
|
||||
url = "https://example.com?taco=bell&taco_count=3"
|
||||
=> "https://example.com?taco=bell&taco_count=3"
|
||||
```
|
||||
|
||||
Let's parse the URL with `URI`:
|
||||
|
||||
```ruby
|
||||
> URI(url)
|
||||
=> #<URI::HTTPS https://example.com?taco=bell&taco_count=3>
|
||||
```
|
||||
|
||||
Then grab the `query` part of that `URI`:
|
||||
|
||||
```ruby
|
||||
> URI(url).query
|
||||
=> "taco=bell&taco_count=3"
|
||||
```
|
||||
|
||||
This is an unparsed string. In a Rails context, this can be parsed with
|
||||
`Rack::Utils.parse_nested_query`:
|
||||
|
||||
```ruby
|
||||
> query_params = Rack::Utils.parse_nested_query(URI(url).query)
|
||||
=> {"taco"=>"bell", "taco_count"=>"3"}
|
||||
```
|
||||
|
||||
And now we have a hash of values we can inspect:
|
||||
|
||||
```ruby
|
||||
> query_params["taco_count"]
|
||||
=> "3"
|
||||
```
|
||||
|
||||
Be sure to do _string_ and not _symbol_ hash access here.
|
||||
|
||||
These steps can be wrapped up into a method:
|
||||
|
||||
```ruby
|
||||
module UrlHelpers
|
||||
def query_params(url)
|
||||
unparsed_query_params = URI(url).query
|
||||
Rack::Utils.parse_nested_query(unparsed_query_params)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
[source](https://stackoverflow.com/a/3218018/535590)
|
||||
Reference in New Issue
Block a user