Shorter version of Dir [File.join (File.dirname (__ FILE__) "," subdirectory / ** / *. Rb ")]?

This is a bit of a micro-question, but every time I create a stone and need to download all the files under a subdirectory for some kind of reflective purpose (or just a quick and dirty pre-load), I ask myself "Of course, should there be a cleaner path?" Referring to this general diagram:

Dir[File.join(File.dirname(__FILE__), "subdirectory/**/*.rb")].each { |f| require f } 

You must call File.dirname on __FILE__ , which makes it unnecessarily verbose. You cannot use the relative path inside the gem, since you do not know where you are loading from.

+6
source share
1 answer

What ruble are you using? With ruby ​​1.9 you can use require_relative .

 require_relative 'subdirectory/file1.rb' require_relative 'subdirectory/file2.rb' #... 

But you must know the files. require_relative will not work with all files in a subdirectory. But I would not recommend using such a general reading in a gem. You need to know what you are downloading.

If you really want this, you can use something like this:

 Dir.chdir(File.dirname(__FILE__)){ Dir["**/*.rb"].each { |f| require_relative f } } 

With ruby ​​1.8 this should work:

 Dir.chdir(File.dirname(__FILE__)){ Dir["./**/*.rb"].each { |f| require f } } 

As for File.join, there are some things for Windows: File.join creates a path, so the OS can use it. On unix, the path separator is / , in windows \ . But, as you already wrote: ruby ​​understands / , so this does not matter in windows. But what happens if you work with Classic Mac OS? There it is : (see Wikipedia Path_ (calculations) ). So it's better to use join, (or you are using my version of Dir.chdir)

+1
source

Source: https://habr.com/ru/post/899849/


All Articles