tags:

views:

426

answers:

1

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.

+4  A: 

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 class Foo in foo.rb, in bar.rb I would have the line require 'foo'.

If you are using Rails, this include often happens automagically

Edit: clarification of file layout

#file: foo.rb
class Foo
  def initialize
    puts "foo"
  end
end

#file: bar.rb
require 'foo'

Foo.new

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.

Ben Hughes
thanks, very helpful. could you clarify that last sentence? it seems you may have had a typo(?).If class foo is stored in bar.rb, i require 'foo' in bazcontroller.rb?Then foo.new is usable in bazcontroller.rb?