2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsバージョンアップで `URI.encode` と `URI.escape` が使えなくなった問題とその解決策

Posted at

Railsアプリをバージョンアップした際に、URI.encodeURI.escape が非推奨・廃止されるため、エンコードの方法を変更する必要が出てきます。この問題とその解決策について、コード例を交えて解説します。


問題の発生

Railsをバージョンアップした後、次のようなコードで問題が発生することがあります。

address = "#{params[:address_line1]}#{params[:city]}#{params[:address_line2]}"
target_uri = URI.escape("https://api.example.com/location?address=#{address}&key=#{API_KEY}")

このコードは URI.escape の廃止によりエラーが発生します。


解決策: URI.encode_www_form_component を使用

すべてのURLをエンコードするのではなく、パラメータ部分のみをエンコードします。

変更後

address = URI.encode_www_form_component("#{params[:address_line1]}#{params[:city]}#{params[:address_line2]}")
target_uri = "https://api.example.com/location?address=#{address}&key=#{API_KEY}"

これにより、正しいリクエストを生成できます。


上記のように、エンコード対象を変更することで、Railsバージョンアップによるエラーを回避できます。

まとめ

Railsのバージョンアップに伴い、URI.encodeURI.escape が使えなくなった場合は、URI.encode_www_form_component を使うことで、パラメータのみをエンコードして問題を解消することができます。バージョンアップ時には、これらの変更に注意して、コードの互換性を保つようにしましょう。


2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?