I’m trying to write a game in Ruby (not Rails) as a way to teach it to myself better. (Meaning, I’d like to do this right, but if I’m trying to shoehorn something that just won’t work into Ruby, I’ll switch languages.) I’m running into a problem with require order, and I’m wondering if there’s a clean way to do the following.
Here’s my structure so far:
game
Gemfile
src
models
character.rb
game_object.rb
init.rb
Instead of listing each file individually, init.rb requires files like this:
Dir['./src/**/*.rb'].each do |app|
require app
end
game_object.rb is, so far, very simple, but character.rb looks like this:
module Game
class Character < Game::GameObject
attr_accessor :name
def initialize(name)
@name = name
end
end
end
Unfortunately, if I do that, I get “uninitialized constant Game::GameObject (NameError)”, unless I explicitly require game_object before other files.
It seems to me that I have a few options here:
- Load game_object (and other superclassees) in init.rb before others.
- Require game_object in character.rb, which seems problematic because depending on which path I use, my understanding is that it may load the file multiple times.
- Load each file individually and manage the order completely manually so I have full control.
These all seem to be more complicated than it should be. Is there a cleaner way?
Just putting it out there: more code does not mean “dirty”, just as often as less code does not mean “clean.”
Requiring your files manually will give you less headache in the long run—it solves load order issues and prevents you from requiring files you don’t actually want. Plus, anyone looking at your code later on has a nice, clean manifest of what’s being loaded in your app.
My suggestions:
srcfolder, it’s redundant—your Ruby app is all source.Example:
You are writing specs / tests, aren’t you?
Then, in
lib/game.rb:And in your init:
Much cleaner, much easier to extract from later on and should solve your problem.