Rails: Converting URL strings to params? - ruby-on-rails

I know Rails does this for you, but I have a need to do this myself for examples. Is there a simple, non-private method available that takes a string and returns the hash of params exactly as Rails does for controllers?

Using Rack::Utils.parse_nested_query(some_string) will give you better results since CGI will convert all the values to arrays.

I found a way after a more intense Google search.
To convert url string to params:
hash = CGI::parse(some_string)
And (as bonus) from hash back to url string:
some_string = hash.to_query
Thanks to: https://www.ruby-forum.com/topic/69428

In model you can write a query like
def to_param
"-#{self.first_name}" +"-"+ "#{self.last_name}"
end
More info
http://apidock.com/rails/ActiveRecord/Base/to_param
It will generate a url like http://ul.com/12-Ravin-Drope
More firendly url you can consult
https://gist.github.com/cdmwebs/1209732

Related

Storing/Retrieving values in a Rails cookie and in different controller [duplicate]

I am trying to store an array on rails an getting error on the decoding.
I use cookies[:test] = Array.new
And when I am trying to decode
#test = ActiveSupport::JSON.decode(cookies[:test])
I am getting an error.
Whats the proper way to achieve what I am trying to ?
When writing to the cookie I usually convert the array to a string.
def save_options(options)
cookies[:options] = (options.class == Array) ? options.join(',') : ''
end
Then I convert back into an array when reading the cookie.
def options_array
cookies[:options] ? cookies[:options].split(",") : []
end
I'm not sure if this is "the right way" but it works well for me.
The "Rails way" is to use JSON.generate(array), since it's what is used in the second example in the Cookies docs:
# Cookie values are String based. Other data types need to be serialized.
cookies[:lat_lon] = JSON.generate([47.68, -122.37])
Source: http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html
When you want to read it back, just use JSON.parse cookies[:lat_lon] for example, and it'll provide you an array.
Use session, not cookies. You don't have to decode it, rails handles that for you. Create the session the same way you already are:
session[:test] = Array.new
and when you need it, access it like normal
session[:test]
# => []

Unable to convert url params string to hash and then back to url string

Input is a params string (Input format cannot be changed)
something=1,2,3,4,5&something_else=6,7,8
Expected Output:
something=1,2,3,4,5&something_else=6,7,8
What I am doing:
params = 'something=1,2,3,4,5'
CGI::parse(params)
CGI.unescape(CGI.parse(params).to_query)
And I am getting this as output:
something[]=1,2,3,4,5
When I did CGI::parse(params)
I am getting this : {"something"=>["1,2,3,4,5"]}
which is wrong because it is not an array, something is a string which is "1,2,3,4,5" but it is being converted as array when I did CGI parse.
The reason I need to do CGI parse is because I need to manipulate the url PARAMS.
Is there any other possible way where I can convert it in the right way and maintain the params format?
The CGI module is a complete dinosaur and should probably be thrown in the garbage because of how bad it is, but for some reason it persists in the Ruby core. Maybe some day someone will refactor it and make it workable. Until then, skip it and use something better like URI, which is also built-in.
Given your irregular, non-compliant query string:
query_string = 'something=1,2,3,4,5&something_else=6,7,8'
You can handle this by using the decode_www_form method which handles query-strings:
require 'uri'
decoded = URI.decode_www_form(query_string).to_h
# => {"something"=>"1,2,3,4,5", "something_else"=>"6,7,8"}
To re-encode it you just call encode_www_form and then force unescape to undo what it's correctly doing to handle the , values:
encoded = URI.unescape(URI.encode_www_form(decoded))
# => "something=1,2,3,4,5&something_else=6,7,8"
That should get the effect you want.

Get query string from extract URL if exists

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
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]

Parse a string as if it were a querystring in Ruby on Rails

I have a string like this:
"foo=bar&bar=foo&hello=hi"
Does Ruby on Rails provide methods to parse this as if it is a querystring, so I get a hash like this:
{
:foo => "bar",
:bar => "foo",
:hello => "hi"
}
Or must I write it myself?
EDIT
Please note that the string above is not a real querystring from a URL, but rather a string stored in a cookie from Facebook Connect.
The answer depends on the version of Rails that you are using. If you are using 2.3 or later, use Rack's builtin parser for params
Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}
If you are on older Rails, you can indeed use CGI::parse. Note that handling of hashes and arrays differs in subtle ways between modules so you need to verify whether the data you are getting is correct for the method you choose.
You can also include Rack::Utils into your class for shorthand access.
The
CGI::parse("foo=bar&bar=foo&hello=hi")
Gives you
{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
Edit:
As specified by Ryan Long this version accounts for multiple values of the same key, which is useful if you want to parse arrays too.
Edit 2:
As Ben points out, this may not handle arrays well when they are formatted with ruby on rails style array notation.
The rails style array notation is: foo[]=bar&foo[]=nop. That style is indeed handled correctly with Julik's response.
This version will only parse arrays correctly, if you have the params like foo=bar&foo=nop.
Edit : as said in the comments, symolizing keys can bring your server down if someone want to hurt you. I still do it a lot when I work on low profile apps because it makes things easier to work with but I wouldn't do it anymore for high stake apps
Do not forget to symbolize the keys for obtaining the result you want
Rack::Utils.parse_nested_query("a=2&b=tralalala").deep_symbolize_keys
this operation is destructive for duplicates.
If you talking about the Urls that is being used to get data about the parameters them
> request.url
=> "http://localhost:3000/restaurants/lokesh-dhaba?data=some&more=thisIsMore"
Then to get the query parameters. use
> request.query_parameters
=> {"data"=>"some", "more"=>"thisIsMore"}
If you want a hash you can use
Hash[CGI::parse(x).map{|k,v| [k, v.first]}]

how to parse multivalued field from URL query in Rails

I have a URL of form http://www.example.com?foo=one&foo=two
I want to get an array of values ['one', 'two'] for foo, but params[:foo] only returns the first value.
I know that if I used foo[] instead of foo in the URL, then params[:foo] would give me the desired array.
However, I want to avoid changing the structure of the URL if possible, since its form is provided as a spec to a client application. is there a good way to get all the values without changing the parameter name?
You can use the default Ruby CGI module to parse the query string in a Rails controller like so:
params = CGI.parse(request.query_string)
This will give you what you want, but note that you won't get any of Rails other extensions to query string parsing, such as using HashWithIndifferentAccess, so you will have to us String rather than Symbol keys.
Also, I don't believe you can set params like that with a single line and overwrite the default rails params contents. Depending on how widespread you want this change, you may need to monkey patch or hack the internals a little bit. However the expeditious thing if you wanted a global change would be to put this in a before filter in application.rb and use a new instance var like #raw_params
I like the CGI.parse(request.query_string) solution mentioned in another answer. You could do this to merge the custom parsed query string into params:
params.merge!(CGI.parse(request.query_string).symbolize_keys)

Resources