LoginSignup
0
0

More than 1 year has passed since last update.

URI.encodeでundefined method 'gsub' for nil:NilClass

Last updated at Posted at 2022-05-26

この記事のまとめ

  • URI.encodeメソッドの引数にnil渡すとundefined method 'gsub' for nil:NilClass エラーが出る
  • URI.encodeではnil避けがされない
  • URI.encode自体が非推奨なのでURI.encode_www_form_componentを使おう

実際に起こった問題

  • URI.encodeメソッドで、URLをエンコーディングしようとした
  • しかし500エラーが発生した。
  • スタックトレース見ると、undefined method 'gsub' for nil:NilClass が出ていた

該当コード:

url = post.url
post.url #nil 

URI.encode(post.url) #undefined method 'gsub' for nil:NilClass

対応

  • URI.encode_www_from_componentを代わりに使おう
URI.encode(nil) # => NoMethodError: undefined method `gsub' for nil:NilClass
URI.encode_www_form_component(nil) # => ""
  • 何かしらの諸事情でURI.encodeを使う場合、nilよけして使うしかないかも。
0
0
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
0
0