Reputation: 23
I'm kinda new to Ruby, so I'm not even sure if what I'm doing is best practice. Right now I am trying to define a function import that resides in a module on something.rb: require 'rexml/document'
module MyModule
def import(file)
Document.new(File.new(file))
end
end
I have another file somethingelse.rb that calls on file something.rb that will use function import require 'something.rb'
class MyClass
include MyModule
def initialize(file)
@myFile = import(file)
end
end
The problem only arises when I try to import the module from another file. When I use the module in the same file, everything works according to what you'd expect. The errors I get are:
usr/lib/ruby/1.8/rexml/dtd/elementdecl.rb:8: warning: already initialized constant PATTERN_RE
XMLTest.rb:9: uninitialized constant MyModule (NameError)
What am I doing wrong?
Upvotes: 2
Views: 4614
Reputation: 283
you can you use require_relative to import the file that has your module use include to add the module in the class to access the module
class MyClass
include somethingModuleName
end
Upvotes: 0
Reputation: 124449
You need to require the other file you're trying to load in your first file, Ruby won't do that for you automatically. So if your module is in a file named "something.rb":
require "something"
class MyClass
include MyModule
def initialize(file)
@myFile = import(file)
end
end
Upvotes: 3
Reputation: 441
try changing your rexml require to require_once.
So:
require_once 'rexml/document'
Upvotes: 0