ruby-on-rails – Japanese URL encoding problem in rails

Question: Question:

Currently, I am using a Japanese URL on a site developed with rails.
I have generated a shared URL for facebook with request.url.
I get the following error and it doesn't work.

incompatible character encodings: UTF-8 and ASCII-8BIT

Many sites have solved it by the following method.


To prevent forgetting to write, do not encode using force_encoding("utf-8") every time
I want to override the method itself in request.url and encode it.

How can I override the existing request.url method?

Answer: Answer:

This can be achieved by using a technique called around aliasing.
Try putting the following code under lib and loading it when Rails starts.
(Confirmed with rails 4.2.3.)

class ActionDispatch::Request
  alias_method :__url, :url
  def url

Save the url method of request with another name, and then return the URL encoded by the new url method.

However, please note that the behavior of the part that originally called the url method (including in Rails!) May change. (Maybe something is wrong)

If you know where to generate the shared URL for facebook, I think it's safer to create a helper that returns the encoded URL obediently.

Scroll to Top