Removing part of a URL from Ruby

Removing a query string from a URL in Ruby can be done as follows:

url.split('?')[0]

Where url is the full URL, including the query string (e.g. url = http://www.domain.extension/folder?schnoo=schnok&foo=bar).

Is there a faster way to do this, i.e. without using split, but instead of using Rails?

edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=barto http://www.domain.extension/folder.

EDIT: I used:

url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
parsed_url = URI.parse(url)
new_url = parsed_url.scheme+"://"+parsed_url.host+parsed_url.path
+3
source share
4 answers
 url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
 u = URI.parse(url)
 p = CGI.parse(u.query)
 # p is now {"schnoo"=>["schnok"], "foo"=>["bar"]}

Take a look at: how to get the query string from the passed url to ruby ​​on rails

+6
source

, fragment query nil URL.

parsed = URI::parse("http://www.domain.extension/folder?schnoo=schnok&foo=bar#frag")
parsed.fragment = parsed.query = nil
parsed.to_s

# => "http://www.domain.extension/folder"
+10

You can get performance with regex

'http://www.domain.extension/folder?schnoo=schnok&foo=bar'[/[^\?]+/]

#=> "http://www.domain.extension/folder"
+3
source

It may not be necessary to split the url. When you visit this link, you pass two parameters to the background code:

http://www.domain.extension/folder?schnoo=schnok&foo=bar params[:schnoo]=schnok params[:foo]=bar

Try to keep track of your journal and you will see them, and you can use them directly in the controller.

0
source

All Articles