rails server confused when class name equals module name

177 views Asked by At

[preface: This question is mostly idle curiosity -- there are clear workarounds -- but an answer might give me insight into something fundamental I don't understand.]

I've been using a namespaced model where the class name is also the module name, like this:

# file: external.rb
module External
  require 'external/external.rb'
  require 'external/other.rb'
end

# file: external/external.rb
module External
  class External < ActiveRecord::Base ; end
end

# file: external/other.rb
module External
  class Other < External ; end
end

When I run this in the rails console, there's no problem. But when I run it under the server, I get the error:

ActionView::Template::Error (superclass must be a Class (Module given)):

on the line class Other < External. Evidently it's confusing the class name with the module name. Why is this? Since the class definition is inside the scope of the External module, shouldn't this be interpreted unambiguously as class External::Other < External::External?

aside

Of course there are a couple of ways to fix this. One is to fully qualify the class name, as in:

module External
  class Other < External::External ; end
end

The more familiar approach, and the way I ended up going, was to simply rename the External class to Base:

# file: external.rb
module External
  require 'external/base.rb'
  require 'external/other.rb'
end

# file: external/base.rb
module External
  class Base < ActiveRecord::Base ; end
end

# file: external/other.rb
module External
  class Other < Base ; end
end

... but I'm still curious why the server got confused (and the console didn't).

0

There are 0 answers