I just started learning Ruby coming from Java. In Java you would use packages for a bigger projects. Is there anything equivalent to that in Ruby? Or what is the best way to achieve a package like setting?
The way I’m doing it right now is ‘load’ing all the needed class into my new Ruby file. Isn’t there a way to tell my current Ruby class to use all other Ruby classes in the same folder?
Cheers,
Mike
There’s three kinds of package loading in Ruby:
requireautoloadgemThe
requiremethod is the most direct and has the effect of loading in and executing that particular file. Since that file may go on torequireothers, as a matter of convenience, you may end up loading in quite a lot at once.The
autoloadmethod declares a module that will be loaded if you reference a given symbol. This is a common method to avoid loading things that you don’t need, but making them automatically available if you do. Most large libraries use this method of loading to avoid dumping every single class into memory at once.The
gemapproach is a more formalized way of packaging up a library. Although it is uncommon for applications to be split up into one or more gems, it is possible and provides some advantages. There’s no obligation to publish agemas open-source, you can keep it private and distribute it through your own channels, either a private web site orgitrepository, for instance, or simply copy and install the.gemfile as required.That being said, if you want to make a library that automatically loads a bunch of things, you might take this approach:
This would load all the
.rbfiles inlib/examplewhen you callrequire 'example'.