whargrove whargrove - 5 months ago 29
Ruby Question

LoadError: Unable to load constant

I have a module with a class that shares a name with a class from the ruby standard library. My class needs to call the class and I'm getting a LoadError.

require 'csv'

module Generator
class CSV
def generate_and_write
::CSV.open(filename) {
# some functionality
}
end
end
end


When I call
Generator::CSV.new.generate_and_write
I get a LoadError exception that states:

Unable to autoload constant Generator::CSV, expected /app/services/generator/csv.rb to define it (LoadError)


The exception is coming from:

vendor/bundle/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:495:in 'load_missing_constant'


When debugging the app, a RunTime exception is thrown when loading the class:

::CSV = {RunTimeError} Circular dependency detected while autoloading constant CSV.

My
config/application.rb
has
config.autoload_paths << Rails.root.join('app', 'services', 'generator')
to ensure the service classes are auto loaded with the rest of the app.

How can I call to the standard library CSV class without conflicting with the name of my class?

Answer

I resolved this issue by renaming the Generator module to FileGenerators. (I am sure FileGenerator would have worked as well but it makes more sense to have a plural module because it contains multiple FileGenerators.)

module FileGenerators
  class CSV < FileGenerators::Base
    def generate_and_write
      ::CSV.open {
        # ...
      }
    end