What is the correct way to deal with identically named ruby source files and ensuring the correct file is loaded by a given require statement?
Background
I want to make use of the ruby-geometry gem in my Rails 3 app.
I’m attempting to make use of the ruby-geometry Polygon class:
require 'geometry' # the main ruby-geometry gem file
module SomeModule
def SomeMethod(vertices)
polygon = Geometry::Polygon.new(vertices)
# Do some stuff with polygon...
end
end
However, whenever I attempt to run this code I get the following error:
NameError: uninitialized constant Geometry::Polygon
This is strange because I seem to be able to work with any of the other ruby-geometry classes without a problem (e.g. Geometry::Point, Geometry::Segment).
The Problem
The problem is that my app contains a source file named polygon.rb (contains an ActiveRecord model) and so does the ruby-geometry gem. So when the ruby-geometry gem requires its own polygon.rb it ends up loading my app’s polygon.rb instead. Presumably this is all down to the order in which ruby searches through directories.
What is the "proper" approach to resolving this naming clash?
Obviously within code you can use modules to differentiate between namespaces to resolve class name clashes. Is there a simple way to differentiate between identically-named source files when require-ing them?
IMHO this is an error in the geometry gem implementation. It is relying in the
$LOAD_PATHenvironment variable to decide where its requested files are. I rather would prefer to userequire_relativeor using theFile.dirname(__FILE__)value to require relative path files in my gems.For solving your issue you can require the geometry gem before Rails is adding its own paths to the
$LOAD_PATHenvironment variable.One way to do this that has worked to me is explicitly require this gem in the
GEMFILE:Another way would be to remove your
app/modelspath from the$LOAD_PATHarray before require the geometry gem:But this is ugly as hell.