6

Possible Duplicate:
How do I easily parse a URL with parameters in a Rails test?

sorry for my english...

I have in my archives.rb model a method to get all src attributes from a html content, I am getting src's like:

http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142

I need to get the params from that url, specifically: id, x, y

Thanks, Regards.

Community
  • 1
  • 1
el_quick
  • 4,656
  • 11
  • 45
  • 53

3 Answers3

19

The correct approach :

url = "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
uri = URI::parse(url)
id = uri.path.split('/')[4]
params = CGI::parse(uri.query)
DGM
  • 26,629
  • 7
  • 58
  • 79
3

In your controller you can do 'params[:x]' and 'params[:y]'. For example:

x = params[:x]
y = params[:y]
Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
thenengah
  • 42,557
  • 33
  • 113
  • 157
  • 1
    thanks, but ... I can't do that, first: my code is in a model, and second the url's are string extracted from html text code. – el_quick Aug 10 '11 at 15:06
-21

It might be done using some regexp for example

irb(main):011:0> s = "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
=> "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
irb(main):012:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,1]
=> "28"
irb(main):013:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,2]
=> "142"
irb(main):014:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,3]
=> "142"
irb(main):015:0>
Bohdan
  • 8,298
  • 6
  • 41
  • 51
  • 2
    There are so many ways this could fail. Let's not use flaky Regex when robust parsers already exist. – Marc-André Lafortune Aug 10 '11 at 15:25
  • such a poor answer, use CGI parse as explained in the dup answer link. – DGM Aug 10 '11 at 15:58
  • I disagree that my answer is **poor** and DGM's one is **correct** since both approaches depend on a structure of the url, mine to get all three params and DGM's to get and id. Both will fail if the url is different. I do agree that using CGI to get x and y values looks pretty. – Bohdan Sep 22 '16 at 03:42