Is it possible to give a sub-module the same name as a top-level class?

前端 未结 3 706
忘了有多久
忘了有多久 2020-12-16 11:07

Background:

  • ruby thinks I'm referencing a top-level constant even when I specify the full namespace
  • How do I refer to a submodule's "full
3条回答
  •  既然无缘
    2020-12-16 11:41

    Here's another fun example:

    module SomeName
      class Client
      end
    end
    
    module Integrations::SomeName::Importer
      def perform
        ...
        client = ::SomeName::Client.new(...)
        ...
      end
    end
    

    That produces:

    block in load_missing_constant': uninitialized constant Integrations::SomeName::Importer::SomeName (NameError)

    Ruby (2.3.4) just goes to the first occurrence of "SomeName" it can find, not to the top-level.

    A way to get around it is to either use better nesting of modules/classes(!!), or to use Kernel.const_get('SomeName')

提交回复
热议问题