← Articoli

File.exists? e Dir.exists? su Ruby 3.2, la soluzione

Se provate ad aggiornare a Ruby 3.2 potreste vedere questo errore:

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>'

Oppure quello per 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>'

La soluzione migliore è usare semplicemente File.exist? e Dir.exist? al posto di File.exists? e Dir.exists?,
perché questi ultimi erano deprecati almeno da Ruby 2.3 e sono stati rimossi in Ruby 3.2

Spesso questi metodi erano usati in gem che non si possono aggiornare facilmente. Per fortuna usiamo Ruby, quindi esiste una soluzione semplice, che ho inserito in una gem.

Come fare il monkey patch:

class File
  def self.exists?(filename)
    self.exist?(filename)
  end
end

Questo codice deve essere eseguito prima di qualsiasi codice che usi il metodo File.exists.
Per semplificare le cose l’ho impacchettato nella gem file_exists.

Basta

gem install file_exists

e includerla con

require 'file_exists'

prima di tutto il resto del codice.