whargrove whargrove - 7 months ago 40
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

When I call
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.

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?


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 {
        # ...