Skip to content

Instantly share code, notes, and snippets.

@islahul
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save islahul/c418fdeea0fafa344c7a to your computer and use it in GitHub Desktop.
Save islahul/c418fdeea0fafa344c7a to your computer and use it in GitHub Desktop.
URI Encoding difference between Rails and JavaScript on handling Hash

Rails

> URI.encode('http://localhost/asflm#aflskm?lkml=klm#lkml')

"http://localhost/asflm%23aflskm?lkml=klm%23lkml"

In Rails use Addressable::URI.escape directly to perform a great encoding taking care of all parts of url

> Addressable::URI.escape('http://local/as host/asflm#aflskm?lkml=kl m#lkml')

"http://local/as%20host/asflm#aflskm?lkml=kl%20m%23lkml"

For multiple params it is better to split the URL and convert query params to a params key-value hash and use it in

> Addressable::URI.form_encode({'asf' => 'asflmk#saf' ', 'asg' => 'asfasg #asgasg'})

"asf=asflmk%23saf%0D%0A&asg=asfasg+%23asgasg"


**JavaScript**

> encodeURI("http://localhost/asflm#aflskm?lkml=klm#lkml")

"http://localhost/asflm#aflskm?lkml=klm#lkml"


Best strategy here to deal with these is to split('?') the URL into path and query params. And then apply Rails-like encoding(encodeURIComponent in JavaScript) on the query params and JavaScript encoding on the path.

Ref: http://www.rubydoc.info/gems/addressable/2.2.4/Addressable/URI#form_encode-class_method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment