The Rubygame Book Part 4

From Kibabase

Jump to: navigation, search
Home Beginning Back Next End
Back to Table of Content Jump to Beginning Back Next Jump to End(Part 7)

The dependencity system is going to be put into test drive mode!

Contents

First, rbpong.rb

The rbpong.rb needed to be written first so that we can actually launch the application.

 file: rbpong.rb on top level of the rbpong directory
    require"config/environment.rb"

Require Dependencity

Require the dependencity library so that we can use it to load other code.

 file: config/environment.rb
    require"rubygems"
    require"rubygame"
    require"shoulda"
    require"yaml"
    require"lib/dependencity/dependencity.rb"
    include Rubygame
    TTF.setup()

Laying the Groundwork for a new Library

Since we need something to test, let go ahead and create a new library in advance. Call this directory, events in lib.

At the heart of the events library is called the Event Loop class.

 file: lib/events/event_loop.rb
    class EventLoop
      def initialize
      end
    end

To fully test the dependencity library, we create a new class called Mode which requires Registrar. Since Registrar will needed to be loaded first, we'll use top as our initial rule.

 file: lib/events/mode.rb
    class Mode < Registrar
      def initialize
        super()
      end
    end
 file: lib/events/registrar_top.rb
    class Registrar
      def initialize
      end
    end

Using Dependencity

Now that we got something to test, let write some code to load them up.

 file: config/environment.rb
    loader = Dependencity.new()
    loader.add_rule("top")      #Add the rules first!
    loader.add_dir("lib/events")
    loader.process_directories()

Now, execute the program at top level of the rbpong directory.

 ruby rbpong.rb

The output should be able to let you see registrar getting loaded first and then the rest, alphabetically and the program should exit pretty quickly.

Ignoring Files

Let see what happen if you ommit a file by using the ignore method.

 file: config/environment.rb
    loader.ignore("lib/events/event_loop.rb")

Write this method just before the process_directories method.

Run the program again, by using the program execution example mentioned in the Using Dependencity section.

The output should ommit lib/events/event_loop.rb, which mean the program didn't load that file at all!

Once you're done with the experiment, make sure to clean up the mess by deleting the ignore method from environment.rb.

Conclusion

This dependencity library will save a lot of energy that goes into adding to a new file and save energy for tinkering with other part of the codebase. The benefit may not seem much like right now, but it will start to add up later in the book, especially as we add lot of files to the codebase. Proceed to Part 5 for a theory of events handling.

Personal tools