For a while I had been including an entire class inside of a Ruby module. Apparently this is not what I am supposed to do. It appears that the point of a module is to store functions which can then be included as methods in a new class.
I don’t want this. I have a class that I want to keep in a separate file which I can access from other files. How can I do this?
Thanks.
Modules serve a dual purpose as a holder for functions and as a namespace. Keeping classes in modules is perfectly acceptable. To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put
require 'name_of_file_with_class'at the top. For instance, if I defined classFooinfoo.rb, inbar.rbI would have the linerequire 'foo'.If you are using Rails, this include often happens automagically
Edit: clarification of file layout
…
If you are in Rails, put these classes in
lib/and use the naming convention for the files of lowercase underscored version of the class name, e.g.Foo->foo.rb,FooBar->foo_bar.rb, etc.As of ruby version 1.9 you can use
require_relative, to require files relatively to the file you are editing.