Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Ruby's file related types string-based (stringly typed)?

e.g. Dir.entries returns an array of strings vs an array containing File or Dir instances. Most methods on Dir and File types. The instances are aneamic in comparison.

There is no Dir#folders or Dir#files - instead I explicitly

  1. loop over Dir.entries
  2. build the path (File.expand_path) for each item
  3. check File.directory?

Simple use-cases like get all .svg files in this directory seem to require a number of hoops/loops/checks. Am I using Ruby wrong or does this facet of Ruby seem very un-ruby-ish?

like image 927
Gishu Avatar asked Jan 13 '17 07:01

Gishu


1 Answers

Depending on your needs, File or Dir might do just fine.

When you need to chain commands and (rightfully) think it feels un-ruby-ish to only use class methods with string parameters, you can use Pathname. It is a standard library.

Examples

Dirs and Files

require 'pathname'

my_folder = Pathname.new('./')
dirs, files = my_folder.children.partition(&:directory?)
# dirs is now an Array of Pathnames pointing to subdirectories of my_folder
# files is now an Array of Pathnames pointing to files inside my_folder

All .svg files

If for some reason there might be folders with .svg extension, you can just filter the pathnames returned by Pathname.glob :

svg_files = Pathname.glob("folder/", "*.svg").select(&:file?)

If you want a specific syntax :

class Pathname
  def files
    children.select(&:file?)
  end
end

aDir = Pathname.new('folder/')
p aDir.files.find_all{ |f| f.extname == '.svg' }

Iterating the Directory tree

Pathname#find will help.

like image 99
Eric Duminil Avatar answered Oct 16 '22 15:10

Eric Duminil