Monkey Patching - Find all files in a folder with Ruby

Written by Brett Veenstra

Here is an extension to Ruby’s File class to allow you to search for all files below a specific folder.

class File
    begin
        def self.find(dir, filename="*.*", subdirs=true)
            Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ].select { |x| File.file?(x) }
        end
    end
end

Ruby is amazing that you can Monkey Patch code. Having just started with Ruby yesterday, and I’m sure I’ll find a better to do this in the future, but for now, this is the best I have. This started from a simple script. Notice the little juice at the end that only returns “real files” according to the File API, now it behaves nicely.

sqlfiles = File.find(Dir.pwd, "*.sql")