Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to include a Class in to another class in Ruby: uninitialized constant (NameError)

Lets say I have three classs, each define in its own file. e.g. ClassA in ClassA.rb etc...

class ClassA
  def initialize
  end

  def printClassA
    puts "This is class A"
  end
end

class ClassB
  def initialize
  end

  def printClassB
    puts "This is class B"
  end
end

class ClassC

  def initialize
  end

  def bothClasses
    a = ClassA.new
    b = ClassB.new
    a.printClassA
    b.printClassB
  end
end

As you can see, ClassC needs the other two classes in order to function correctly. I assume, there needs to be a way to import/include/load the other two classes in ClassC.

I'm new to Ruby and I've tried every permutation of load/include/require and I cannot figure out how to get this to run.

I normally just get:

classc.rb:2:in `<class:ClassC>': uninitialized constant ClassC::ClassA (NameError)
    from classc.rb:1:in `<main>'

Or a syntax error with my import/include/require statements.

Using Windows 7, Ruby 1.9.2, RadRails, all files are in the same project and source folder.

I'm sorry if this question is similar to some of the other questions on here, but most of the answers to resolving the "uninitialized constant" is to "just require the file". I've tried and it isn't working.

like image 938
user604886 Avatar asked Feb 06 '11 01:02

user604886


1 Answers

I think your problem is that $:, the variable that controls where require looks for files, no longer includes the current directory in Ruby 1.9.2 and higher (for security reasons). To tell Ruby where to look for the file, you need to do one of:

require_relative 'ClassA' # which looks in the same directory as the file where the method is called

# or #

require './ClassA' # which looks in the current working directory
like image 169
Chuck Avatar answered Nov 16 '22 03:11

Chuck