Class method defined, still undefinded method exeption

Hi

i try to untangle tightly coupled classes. To that end theres a class to
hold all resources that are needed by multiple other classes. Its called
RA for Resource Aggregator.

Moving one central object to that class broke the programm. Here’s the
output:

./video.rb:11:in initialize': undefined methodscreen’ for RA:Class
(NoMethodError)
from ./game.rb:32:in new' from ./game.rb:32:ininitialize’
from ./resourceaggregator.rb:10:in new' from ./resourceaggregator.rb:10 from ./main.rb:3:inrequire’
from ./main.rb:3

RA is pretty big, so i ommit most Methods. Its intended to be a utility
class and has no custom initialize:

class RA
@@xRes = 1280
@@yRes = 800
@@colordepth = 16
@@screen = SDL.setVideoMode(@@xRes, @@yRes, @@colordepth,
SDL::SRCCOLORKEY) #SDL::FULLSCREEN
@@game = Game.new
@@videoManager = VideoManager.new

def self.screen
@@screen
end
end

Here is initialisite from VideoManager

def initialize
@screen = RA.screen
@xOffset = 0
@yOffset = 0
end

~/ruby_programs$ ls

ra.rb
my_prog.rb

ra.rb

class RA
@@screen = ‘hello’

def self.screen
@@screen
end

end

my_prog.rb

require ‘./ra’

class VideoManager
def initialize
@screen = RA.screen
puts “I work just fine”
end
end

VideoManager.new

~/ruby_programs$ ruby my_prog.rb
I work just fine
~/ruby_programs$

Look carefully at the backtrace:

./video.rb:11:in initialize': undefined methodscreen’ for RA:Class
(NoMethodError)
from ./game.rb:32:in new' from ./game.rb:32:ininitialize’
from ./resourceaggregator.rb:10:in new' from ./resourceaggregator.rb:10 from ./main.rb:3:inrequire’
from ./main.rb:3

Notice this line:

from ./resourceaggregator.rb:10:in `new’

It hasn’t finished loading RA yet when it calls VideoManager.new; which,
itself, expects RA to be fully defined.

As a workaround, you could wrap up all the class variable definitions in
an
“init” method, called after the class is defined. Or just move them to
the
bottom of the class.

Thank you, problem solved, understanding gained. Since the call to
RA.screen was only a hack to keep the code running while reworking it,
its gone now.

@7stud:
What are you here for? Do you think he’s faked the error messages or
what?

@Michael:

The problem is that you’re using the RA class before it’s even fully
created. When you call VideoManager.new, which tries to call RA.screen,
the RA class doesn’t have a screen method yet.

So that’s what you’ll have to fix. A simple bugfix would be to put
VideoManager.new and similar method calls at the very bottom of RA’s
class body.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs