Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby separate large source files into multiple files

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.

What I did:

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?

Thanks

EDIT

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

like image 291
Hunter McMillen Avatar asked Sep 27 '26 19:09

Hunter McMillen


1 Answers

In Ruby 1.8.x, the . is part of your load path. So you should at least try to debug that by including something like:

puts $:
require 'GoogleChart'
class BarChart < GoogleChart
end

and load that in an IRB session:

  1. Open the session in your directory proj.
  2. Enter there require 'BarChart'
  3. Look at the result.

For me it is:

c:\apps\ruby\test\proj>irb
irb(main):001:0> require 'BarChart'
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby/1.8
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby/1.8/i386-msvcrt
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby/1.8
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby/1.8/i386-msvcrt
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/1.8
C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/1.8/i386-mingw32
.
=> true

So the require is successful for me, and the . is part of the path (as it should). As you can see, I am working with Ruby 1.8.7, I don't know if anything has changed since 1.8.4 that is relevant here.

So please describe exactly how you run your file:

  • Have you opened a shell to run the file?
  • What is the current working directory of that shell?
  • Do you run by double-clicking it?

It only works when you are in your proj directory and run there (with ruby in your shell path) ruby BarChart.rb.

like image 101
mliebelt Avatar answered Sep 30 '26 08:09

mliebelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!