I am writing a Ruby script which was supposed to be a small thing but
has grown quite large, way to large to have everything crammed into one
source file. So I am trying to separate the project into different
files. I have four classes and I want to put each in its own separate
source file.
I moved all of the classes into their own files so now I have this:
proj/GoogleChart.rb
proj/BarChart.rb
proj/PieChart.rb
proj/GroupedBarChart.rb
Now that they are in other files I am getting uninitialized constant
GoogleChart (NameError) in all of my subclasses on the line where I
inherit from GoogleChart, i.e.
require ‘GoogleChart’
BarChart < GoogleChart
Can anyone tell me what is wrong?
Please Note:
Using ruby version 1.8.4
Also I have tried using the absolute path:
require ‘C:/Documents and Settings/proj/GoogleChart.rb’
and this is still producing a NameError
Thanks for any help
Hunter
On 8/15/2011 09:02, Hunter Mcmillen wrote:
require ‘GoogleChart’
BarChart < GoogleChart
Can anyone tell me what is wrong?
The problem is not the require statement. If that had failed, you would
get a LoadError rather than a NameError, so GoogleChart.rb loaded
successfully.
My guess is that your GoogleChart class is actually within a deeper
namespace, something like Your::Namespace::GoogleChart. Perhaps when
you had everything in the single file, that namespace was enclosing all
your class definitions, so the look up of the GoogleChart name just
worked. Now that you broke everything apart, that namespace apparently
isn’t wrapping the definitions in the new file.
There are 4 solutions I see offhand:
-
Wrap the definition of BarChart within the same namespace as
GoogleChart. e.g.
require ‘GoogleChart’
module Your
module Namespace
class BarChart < GoogleChart
…
end
end
end
-
Explicitly name the full name of GoogleChart. e.g.
require ‘GoogleChart’
class BarChart < Your::Namespace::GoogleChart
…
end
-
Include the namespace of GoogleChart into main. e.g.
require ‘GoogleChart’
include Your::Namespace
class BarChart < GoogleChart
…
end
-
Remove the enclosing namespace from the definition of GoogleChart.
-Jeremy