I'm making a Tweet This link in Rails. The URL I need to generate looks something like this:
http://twitter.com/share?url=http%3A%2F%2Fexample.com&text=Hello%20World
but a bit more complex. Basically a URL with a load of GET parameters appended
It would be nice to use one of Rails' helpers, to generate this link, something like:
url_for("http://twitter.com/share", :url => "http://example.com", :text => "Hello world")
But I haven't found anything that works. Anyone have any ideas?
Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.
GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.
The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
You can call to_query
on Hash in rails which will take care of url encoding etc. So maybe something like this:
params = { :a => "http://google.com", :b => 123 } url = "http://example.com?#{params.to_query}"
I like Brian's answer. Here it is in the form of a method, in case anyone else comes across this.
def url_with_attributes_from_hash(url = "", attr_hash = {}) url == "" or attr_hash == {} ? "#{url.to_s}" : "#{url.to_s}?#{attr_hash.to_query}" end
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