Reputation: 4049
Here's my output:
URI.encode("http://localhost:3000/membership?referer_invite_code=a03478&fee=UVYA")
=> "http://localhost:3000/membership?referer_invite_code=a03478&fee=UVYA"
But I need output to be:
=> "http%3A%2F%2Flocalhost%3A3000..."
The reason is because I'm trying to do an embedded twitter link and twitter doesn't do well with ampersands, so as long as the encoding doesn't replace the &
for the last fee parameter with %26
it won't work. How do I fix this?
WORKING SOLUTION
Rack::Utils.escape("http://localhost:3000/membership?referer_invite_code=a03478&fee=UVYA")
But I guess I'm just curious why URI.encode
did not work
Upvotes: 2
Views: 1552
Reputation: 87
You should use URI.encode_www_form_component
for this purpose instead:
URI.encode_www_form_component "http://localhost:3000/membership?referer_invite_code=a03478&fee=UVYA"
=> "http%3A%2F%2Flocalhost%3A3000%2Fmembership%3Freferer_invite_code%3Da03478%26fee%3DUVYA"
It seems that URI.encode
is intended to encode an entire URI for use as a URI, rather than for use as a parameter within a URI. It is only meant to protect against the use of illegal characters in a URI - not to properly encode URI parameters - so by default it does not encode the reserved characters listed here.
You can find more information in the RubyDoc entry for URI::Escape. URI.escape
takes an optional regular expression as a second argument. The regex specifies which characters should be percent-encoded in the result. If omitted, the default of URI::UNSAFE
is used. In MRI 2.3.1, this amounts to the following:
/[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]]/
As you can see, this will not match any of the reserved characters for a URI. What it will do is protect you from constructing and using a URI that is illegal. For example:
URI.encode "https://test.com"
=> "https://test.com"
URI.encode "https://testçĕÅ.com/"
=> "https://test%C3%A7%C4%95%C3%85.com/"
Upvotes: 1