Paul
Paul

Reputation: 26660

Ruby: multiple files, one "require" clause

I have several classes wrapped into one module to make namespace for them, stored in one file my_namespace.rb.

module MyNamespace
    class Class1
    end

    class Class2
    end

    class Class3
    end

    class Class4
    end

    class Class5
    end
end

This module is pluged in by one clause:

require 'my_namespace'

This module is bloated by now, so I want to split the namespace across several *.rb files in lib folder - one file per class, but am afraid that it will require to use several require clauses - one per class. How to keep one require clause? (Or more exactly: require, include or whatever allows me to use my classes)

Upvotes: 2

Views: 1553

Answers (1)

Max Williams
Max Williams

Reputation: 32943

You can generate your require calls at load time by looking into the folder first. eg

Dir[File.join(Rails.root, "path/to/directory/*.rb")].each {|file| require file }

So, if all of your files were in the "/path/to/directory" folder they'd all get required.

Some people favour dropping the ".rb" part from the end of the require, in which case you would do

Dir[File.join(Rails.root, "path/to/directory/*.rb")].each {|file| require file.gsub(/\.rb$/,"") }

EDIT - updated the paths to be inside the rails project folder, since they probably will be in there somewhere. In the above example, i've assumed that they are in <your project folder>/path/to/directory

There is a potential risk in this approach when using inheritance because files are listed probably in different order than inheritance requires. Even if you manage to name files so that inheritance works in Windows, Linux may sort files in a different order and this will ruin all your efforts. In such case an array of file names is recommended.

Upvotes: 2

Related Questions