Ruby 3.4 で erb2haml
がエラーになる件とその対処法(NoMethodError: undefined method exists?
)
こんにちは。
エンジニア転職を目指している、現役の看護師です。
RailsアプリでERBをHamlに変換しようとerb2haml
のタスクを実行したところ、Ruby3.4でエラーが発生しました。調査・対処して無事変換できたので忘れないように記録しておきます。
環境
- Ruby 3.4.2
- Rails 8.0.2
- erb2haml 0.1.5
発生したエラー
bundle exec rake haml:replace_erbs
Looking for ERB files to convert to Haml...
rake aborted!
NoMethodError: undefined method 'exists?' for module FileTest (NoMethodError)
unless FileTest.exists?(haml_path)
^^^^^^^^
Did you mean? exist?
調べると、Ruby3.4ではFileTest.exists?
が 完全に削除されており、exist?
を使う必要があるらしい。
原因と該当箇所の特定
以下のコマンドで該当箇所を検索
grep -rn "FileTest.exists?" $(bundle show erb2haml)
以下、結果
.../gems/erb2haml-0.1.5/lib/erb2haml/railties/erb2haml.rake:29: unless FileTest.exists?(haml_path)
.../gems/erb2haml-0.1.5/lib/erb2haml/railties/erb2haml.rake:59: unless FileTest.exists?(haml_path)
修正内容
該当ファイルを開く
nano ~/.rbenv/versions/3.4.2/lib/ruby/gems/3.4.0/gems/erb2haml-0.1.5/lib/erb2haml/railties/erb2haml.rake
以下をそれぞれ置き換えします。
- unless FileTest.exists?(haml_path)
+ unless FileTest.exist?(haml_path)
再実行で成功
bundle exec rake haml:replace_erbs
正常にHamlに変換されたようです
自分用メモ
- Rubyのバージョンが上がると、標準メソッドでも容赦なく削除されるので要注意
- 今回みたいにgemが古いとエラーに直結するため、確認していきたい
- Ruby3.4ではFile.exists? / FileTest.exists?は削除されたみたい
→代わりに File.exist? を使う("s" なし)
gemがRubyの最新仕様に追いついてないこともあるので、バージョンアップ後はgemの中身もチェックするようにする