5

Removing the query string from a URL in Ruby could be done like this:

url.split('?')[0]

Where url is the complete 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 rather using Rails?

edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=bar to 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
thejartender
  • 9,339
  • 6
  • 34
  • 51
TTT
  • 6,505
  • 10
  • 56
  • 82
  • 1
    I am not sure if I completely understand your goal. Do you want extract parameters from request in your controller? – Suborx May 02 '12 at 09:12
  • Is this the URL from the current request, or just a completely arbitrary URL? – Andrew Marshall May 02 '12 at 09:14
  • You need to add port if present (and other than 80): `new_url = "#{parsed_url.scheme}://#{parsed_url.host}#{parsed_url.port != 80 ? (':'+parsed_url.port) : ''}#{parsed_url.path}"` – hammady Jun 15 '15 at 05:41
  • @hammady - `+parsed_url.port` won't work without explicit converting to string first. Use `+parsed_url.port.to_s` instead. – silverdr Dec 13 '16 at 10:19
  • @silverdr that's right, didn't test it, should be `(':'+parsed_url.port.to_s)` – hammady Dec 13 '16 at 13:36
  • The OP asks "is there a _faster_ way to do this" -- I think maybe the answer is "no" – user1070300 Aug 30 '23 at 10:41

4 Answers4

17

Easier to read and harder to screw up if you parse and set fragment & query to nil instead of rebuilding the 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"
TTT
  • 321
  • 3
  • 4
7
 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 on the : how to get query string from passed url in ruby on rails

Community
  • 1
  • 1
swati
  • 1,719
  • 10
  • 13
6

You can gain performance using Regex

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

#=> "http://www.domain.extension/folder"
Boris Brodski
  • 8,425
  • 4
  • 40
  • 55
zetanova
  • 481
  • 4
  • 11
0

Probably no need to split the url. When you visit this link, you are pass two parameters to back-end:

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

Try to monitor your log and you will see them, then you can use them in controller directly.

zhongxiao37
  • 977
  • 8
  • 17