These free mini-courses will give you a strong foundation in web development. Track your progress and access advanced courses on HTML/CSS, Ruby and JavaScript for free inside our student portal.
Scroll down...
When working with multiple classes, it's conventional to put them in different files. This very brief lesson will illustrate how to do so.
The file is typically called the Snake Case version of the class name:
# some_class.rb <<< File Name
class SomeClass <<< Class Name
...
end
If you want to pull these separate classes together, you will need to require
each file you would like to use. You already saw require
used in IRB and this is the same method.
require
basically copy-pastes one file into another (with some intelligent handling of duplication). As you can imagine, if you'd like to use three different classes in one file, it might look like this:
# one_class.rb
require './two_class'
require './three_class'
class OneClass
def initialize
two = TwoClass.new
three = ThreeClass.new
end
end
It's often best to have one single file which requires all the other files you need (the "command center") and which contains the initial script you plan to run instead of having each file individually require
those files.
You will often see this pattern used in configuration and setup files for larger frameworks like Rails or gems like RSpec.
Because it can become burdensome to explicitly write out full paths to specific files when you have a more complex application structure, the require_relative
command allows you to write simpler relative paths:
# one_class.rb
require_relative 'two_class'
require_relative 'three_class'
...
The one challenge with working among multiple files comes when you have a nest of classes which all require each other. If these are all in their own files, you can typically get away with simply listing all the require_relative
statements you need atop your parent class.
# somefile.rb
require_relative 'other_class'
require_relative 'third_class'
...
class MainClass
...
end
Rarely, you might run into issues where Ruby throws out a number of UninitializedConstant
errors or those dealing with circular dependencies. Often that is a cue that your architecture is a bit too complicated but it can also typically be solved by being extra careful which order you write your require_relative
statements -- if there is a chain of dependency, try to put the "parent" classes at the top.
The important bits of code from this lesson
require './path/to/filename'
You will break your classes apart into separate files throughout your apps and this will become second nature. In larger applications (and Rails apps), much of this will be taken care of for you behind the scenes by helpful scripts baked into the framework.