Ruby 3.2でのFile.exists?とDir.exists?の回避策
Ruby 3.2にアップグレードしようとすると、次のエラーが表示されることがあります。
irb(main):001:0> File.exists?
(irb):1:in `<main>': undefined method `exists?' for File:Class (NoMethodError)
Did you mean? exist?
from C:/Ruby32-x64/lib/ruby/gems/3.2.0/gems/irb-1.6.2/exe/irb:11:in `<top (required)>'
from C:/Ruby32-x64/bin/irb:25:in `load'
from C:/Ruby32-x64/bin/irb:25:in `<main>'
あるいは、Dir.exists?の場合はこちらです。
(irb):3:in `<main>': undefined method `exists?' for Dir:Class (NoMethodError)
Did you mean? exist?
from C:/Ruby32-x64/lib/ruby/gems/3.2.0/gems/irb-1.6.2/exe/irb:11:in `<top (required)>'
from C:/Ruby32-x64/bin/irb:25:in `load'
from C:/Ruby32-x64/bin/irb:25:in `<main>'
一番良いのは、File.exists?とDir.exists?の代わりにFile.exist?とDir.exist?を使うことです。
これらは少なくともRuby 2.3から非推奨となっており、Ruby 3.2で削除されました。
これらのメソッドは、簡単には更新できないgemの中で使われていることがよくあります。幸い私たちが使っているのはRubyなので、簡単な回避策があります。それをgemにまとめました。
モンキーパッチのやり方:
class File
def self.exists?(filename)
self.exist?(filename)
end
end
これは、File.exists?メソッドを使うどのコードよりも先に実行する必要があります。
もっと簡単に使えるように、file_exists gemにまとめました。
次のコマンドで
gem install file_exists
インストールし、ほかのすべてのコードより前に
require 'file_exists'
で読み込むだけです。