Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding namespaces in Ruby

Tags:

ruby

In the code below:

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

what is the relation between Trace and ZipkinTracer?

like image 992
shijinkui Avatar asked Aug 25 '26 09:08

shijinkui


2 Answers

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.

like image 192
Marek Lipka Avatar answered Aug 27 '26 00:08

Marek Lipka


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!"
like image 38
Boris Stitnicky Avatar answered Aug 26 '26 22:08

Boris Stitnicky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!