4

Python has modules and packages, and packages have __init__.py file, so if I import a package called foo, the interpreter will look for foo/__init__.py.

I came across some ruby code that will include not a module but a directory: require 'core/utilts'. The core and utilts are directories, not single module files. What is the equivalent in ruby to the file __init__.py, or what are the files that are executed when I require a directory like this utilts dir? There are a lot of ruby files under it.

sawa
  • 165,429
  • 45
  • 277
  • 381
user3718463
  • 265
  • 1
  • 7

3 Answers3

6

You can't import directories in Ruby. If you're running require 'core/utils', then there is a file called core/utils.rb. There might also be a directory called core/utils/ but it's utils.rb that is being included via require, and it will in turn likely includes files out of core/utils/.

So, the answer to your question is: No, there is no equivalent to foo/__init__.py, but the same thing can typically be accomplished with foo.rb which includes additional files in foo/.

user229044
  • 232,980
  • 40
  • 330
  • 338
3

ruby is a little different. Usually gems or "libraries" in ruby modify the LOAD_PATH constant which is where the ruby interpreter looks for files when you call require. So a standard gem works by appending the lib directory to the LOAD_PATH and then files can be required that are namespaced inside that directory. It is also a convention that there is usually a file with the same name as the library that can be required and then loads all dependencies.

For example: with the following project.

lib/
 -- core/utils/
 -- core/utils.rb
core_utils.gemspec

you would call:

require "core/utils"

and the utils.rb would load all files within the core/utils path.

sawa
  • 165,429
  • 45
  • 277
  • 381
DataDao
  • 703
  • 6
  • 12
3

Ruby doesn't support loading entire directories, but it's easy to do if need-be:

Dir.glob('lib/*.rb').map do |p|
  require p
end

I used map for this because it'll return the require response, making it possible to see if something failed to load, since require returns true for success and false for failure. Failure/false means the file wasn't loaded because it didn't need to be, usually that is because it already had been by something else. If you don't care about the returned values, use each instead of map.

You could also do the tricks mentioned in "Adding a directory to $LOAD_PATH (Ruby)" and then use require without any path prefixed to the file you want to load.

Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303