11

Is it ruby convention for all files to be in a module with the folder structure (similar to java packages)?

For example, if I have a file structure that looks like

lib/people/utils

would the files in here have the module structure such as:

module People
  module Utils
    # some functionality for People::Utils
  end
end      

The reason I ask is because I've been reading through some rails code, and there seem to be several files that are in a file structure like this, but don't have any module declarations.

I'm guessing this would be so you could use the utility function without having to include People::Utils.

Is there a convention in ruby as to when modules should be used and when they shouldn't?

2 Answers 2

16

It is the standard in Rails. The way Rails loads your models is by looking on the folder structure to guess where classes are. We have the so called autoload_paths.

You can find them by calling in your rails console (this is a bit hacky, there might be an easier way to show them):

app.instance_variable_get(:"@app").instance_variable_get(:"@_all_autoload_paths")

A default Rails app output, without config.autoload_paths += %W(#{config.root}/lib) in your config/application.rb config block would look like this:

["/Users/lunks/Code/rsvp/app/assets",
 "/Users/lunks/Code/rsvp/app/controllers",
 "/Users/lunks/Code/rsvp/app/helpers",
 "/Users/lunks/Code/rsvp/app/mailers",
 "/Users/lunks/Code/rsvp/app/models"]

So, if you have app/models/something/util.rb and you call Something::Util somewhere, it'll look into these paths, find the app/models/ folder with something/util.rb and load this.

Ruby, on the other hand, doesn't care about that. Autoload in plain Ruby works as described on this page. You'll have to either use Autoload or require the files directly (and folder structure won't mean anything).

1
  • And to list autoload_paths in later Rails versions: Rails.application.instance_variable_get(:"@_all_autoload_paths")
    – valk
    Jul 1, 2016 at 10:32
5

It's generally a good idea to put classes and files in a structure like that, because it will make it easier for people to map the name of the class to its definition.

But it can make sense not to do this (ultimately you structure your code however you like). I've occasionally done it when there were lots of small classes all dealing with the same thing, I put them together.

And it can make sense to have a file which does not define a module or class, e.g. a configuration file, or a binary, or a bootstrapping file (file which loads up all the other ones).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.