Understanding namespaces in Ruby

后端 未结 2 1008
爱一瞬间的悲伤
爱一瞬间的悲伤 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:50

    This code does the following thing. First, it instantiates class ZipkinTracer:

    new_instance = Trace::ZipkinTracer.new()
    

    Then, it calls #tracer= method of the Trace module:

    Trace.tracer=( new_instance )
    

    Ruby syntax allows this to be rewritten as

    Trace.tracer = new_instance
    

    In this case, no assignment is happening, but a method ending in = is called. Methods ending in = are allowed in Ruby, used generally for attribute assignment, and they are special in that they always return the assigned value (that is, their argument), regardless of what other return value you might be trying to prescribe:

    class Foo
      def bar=( value )
        puts "Method #bar= called!"
        @bar = value
        puts "Trying to return Quux!"
        return "Quux!"
      end
    
      def bar; @bar end
    end
    
    foo = Foo.new
    foo.bar #=> nil
    foo.bar = "Baz!"
    #=> Method #bar= called!
    #=> Trying to return Quux!
    #=> "Baz!" -- attempt to explicitly return "Quux!" failed
    foo.bar #=> "Baz!"
    

提交回复
热议问题