Understanding namespaces in Ruby

后端 未结 2 1022
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 22:31

In the code below:

::Trace.tracer = ::Trace::ZipkinTracer.new()

what is the relation between Trace and ZipkinTracer

2条回答
  •  盖世英雄少女心
    2020-12-19 22:58

    ZipkinTracer is inside of Trace namespace, like this:

    module Trace
      class ZipkinTracer
      # ...
      end
    end
    

    The :: before constant name means that you point to the root. For example in the following code:

    class Class1
    end
    
    module Module1
      class Class1
      end
    
      def foo
        ::Class1
      end
    end
    

    ::Class1 ensures that you refer to the "root" Class1. If you had:

    def foo
      Class1
    end
    

    the Module1::Class1 would be referred.

提交回复
热议问题