Including a Ruby class from a separate file Including a Ruby class from a separate file ruby ruby

Including a Ruby class from a separate file


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.rbclass Foo  def initialize    puts "foo"  endend

...

#file: bar.rbrequire '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.


You can also use load. Also you use require relative if the file is in the same directory. Read this link for further understanding: http://rubylearning.com/satishtalim/including_other_files_in_ruby.html


When Using Require, inside the string indicate the full path name of the class you are refereing to unless its in the Root Folder of Ruby