I have a callback url string params[:callback]
and I need to append a query string "&result=true"
and redirect the user. The better way I found of doing this is using addressable
but I think the code is too big for task like this especially when we are talking about ruby:
callback = Addressable::URI.parse(params[:callback])
query = callback.query_values
query[:result] = 'true'
callback.query_values = query
redirect_to callback.to_s
Is there a more elegant way of getting the same result as this snippet?
Simply use: echo http_build_url($url, array("query" => "the=query&parts=here"), HTTP_URL_JOIN_QUERY); .
This can be done by using the java. net. URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax. The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.
To append a param onto the current URL with JavaScript, we can create a new URL instance from the URL string. Then we can call the searchParams. append method on the URL instance to append a new URL parameter into it. to create a new URL instance with "http://foo.bar/?x=1&y=2" .
I wan't to bring update to this topic, because any of the solutions didn't work me.
The reason being, that it seems that callback.query_values
returns Nil
if the actual url doesn't have existing query values.
Therefore if you have urls such as: http://www.foo.com
and http://www.foo.com?bar=1
you should use the following code:
url = "http://www.foo.com" # or params[:callback] obviously. :)
callback = Addressable::URI.parse(url)
callback.query_values = (callback.query_values || {}).merge({
result: true
})
redirect_to callback.to_s
Cheers.
url = params[:callback]
redirect_to url + (url.include?('?') ? '&' : '?') + 'result=true'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With