Skip to content

MR11 Multiple Files

Dave Strus edited this page Feb 1, 2016 · 2 revisions

Multiple Files

In this unit, we'll do the following:

  • Define each class in a separate file

We'll learn about the following concepts or tools:

  • Class file naming conventions
  • Directory structure conventions
  • require_relative

Our classes should be in files by themselves. Let's put these files in a lib subdirectory within our project.

Files that contain class definitions should be given the same name as the class, all lowercase, with underscores separating words.

Create a subdirectory called lib...

$ mkdir lib

...create a file for the RosterApplication class...

$ touch lib/roster_application.rb

...and another for the Mutant class.

touch lib/mutant.rb

Now your project's structure should look like this:

.
├── lib
│   ├── mutant.rb
│   └── roster_application.rb
└── roster.rb

Remember, you can use the tree command to display a directory tree in the terminal. Use the command tree . to show the tree for the current directory.

Go ahead and move the class definitions in their respective files. That should leave roster.rb looking like this:

roster.rb

#!/usr/bin/env ruby
require 'pry'

app = RosterApplication.new
app.start

3.times do
  app.collect_mutant_data
end

puts app.mutant_descriptions

If you try to run it, you'll see an error:

./roster.rb:4:in

': uninitialized constant RosterApplication (NameError)`

It no longer knows about the RosterApplication class. We need to require the new file.

require_relative 'lib/roster_application'

Now, RosterApplication doesn't know about Mutant. Let's require that file too.

#!/usr/bin/env ruby
require_relative 'lib/mutant'
require_relative 'lib/roster_application'
require 'pry'

app = RosterApplication.new
app.start

3.times do
  app.collect_mutant_data
end

puts app.mutant_descriptions

Now it's back in a working state, and looking good!