rails, how to get params from url string?

19,418

Solution 1

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>

Solution 2

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)

Solution 3

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

x = params[:x]
y = params[:y]
Share:
19,418
el_quick
Author by

el_quick

Just a developer more.

Updated on July 21, 2022

Comments

  • el_quick
    el_quick almost 2 years

    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.

  • el_quick
    el_quick over 12 years
    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.
  • Marc-André Lafortune
    Marc-André Lafortune over 12 years
    There are so many ways this could fail. Let's not use flaky Regex when robust parsers already exist.
  • DGM
    DGM over 12 years
    such a poor answer, use CGI parse as explained in the dup answer link.
  • Bohdan
    Bohdan over 12 years
    you forgot about an id
  • DGM
    DGM over 12 years
    updated to get the id then. :)
  • DGM
    DGM over 8 years
    edit was wrong, and the suggested edit to fix it was incorrectly rejected. I have corrected it.
  • Bohdan
    Bohdan over 7 years
    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.