1

I'm trying to get the value of a variable, prop, in a query string from a passed URL similar to what the gentleman in this thread did.

It works if there's a query string in the URL but if there isn't I get CGI.parse undefined method 'split' for nil:NilClass error. I did research and the problem is because there is no query to split.

So my question is how can I test for the presence of any query string and then run it through CGI.parse to see if the prop query string is one of them? I assume I could probably do it through Regex but I was hoping there was a Rails solution.

Any help would be appreciated.

Thanx

Code: I'm also trying to get the domain name of the URL referrer. That is why I have that variable in there.

url = request.env['HTTP_REFERER']
encoded_url = URI.encode(url.to_s)
parse = URI.parse(encoded_url)
domain = parse.host
puts domain
params = CGI.parse(parse.query)
puts params['prop'].first

UPDATE: I got the error to go away by adding the attached code. But I'm still wondering if there's a better Rails solution. I'm still fairly new to Rails, so I want to make sure I'm doing it correctly.

if encoded_url.include? "?prop"
    params = CGI.parse(parse.query)
    puts params['prop'].first
end
Community
  • 1
  • 1
chavab_1
  • 237
  • 2
  • 10
  • 1
    Are you sure you've gone through rails tutorial? This is one of the most basic things to do. Every request, doesn't matter which HTTP verb has a `params` hash which you can use in your controller to get the value of the key you need. Combine it then with `.present?` method in if else – Akash Agarwal Nov 04 '16 at 01:11
  • Oh, I thought the params hash was only accessible within a Rails URL. I didn't know it was available for external URLs as well. I came across the SO question which was similar to mine so that's what also lead me to believe that. But it does make sense that it would work in every case. Thanx. – chavab_1 Nov 04 '16 at 04:54
  • Let me know if this worked for you, or not :) – Akash Agarwal Nov 04 '16 at 05:09
  • Yeah, it works. Thanx a lot for your help. – chavab_1 Nov 04 '16 at 17:09

1 Answers1

2

The keys in query string in a URL can be accessed using params[] hash, even if the URL is not present inside the app itself. This is how it is convenient for rails to communicate with the outside world as well. Note that rails treats all the HTTP verbs equally when it comes to usage of params[] hash.
Usage: puts params[:your_key]

Akash Agarwal
  • 2,326
  • 1
  • 27
  • 57