Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a Ruby class from a separate file

Tags:

module

class

ruby

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.

like image 338
user94154 Avatar asked Jun 26 '09 19:06

user94154


People also ask

Should each class be in a separate file?

If you have a class that really needs to be a separate class but is also only used in one place, it's probably best to keep it in the same file. If this is happening frequently, though, you might have a bigger problem on your hands.

Can we include class in Ruby?

Ruby allows you to create a class tied to a particular object. In the following example, we create two String objects. We then associate an anonymous class with one of them, overriding one of the methods in the object's base class and adding a new method.

Can a class inherit from a module Ruby?

The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways. As mentioned, you can find Module in the array Class.


1 Answers

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.

As of ruby version 1.9 you can use require_relative, to require files relatively to the file you are editing.

like image 120
Ben Hughes Avatar answered Sep 22 '22 21:09

Ben Hughes