Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's difference in ::ModuleName::ClassName and ModuleName::ClassName

In ruby, I'm starting to see a pretty normal practice including modules and mixins referenced as ::ModuleName::ClassName, where in the past it was pretty much just ModuleName::ClassName.

What I'd like to get here is a decent understanding of why this practice is being seen more lately and what it does differently.

What's the difference?

What's the benefit (if the prior doesn't answer this)?

Thanks in advance for your input.

like image 944
Jeff Ancel Avatar asked Feb 22 '12 15:02

Jeff Ancel


2 Answers

If you put the :: in the beginning you are referring to the global namespace, if you don't you are referring to your current namespace.

Usually if you don't have a class/module with the same name inside your class/module you would not need to use the :: in the beginning.

class Customer

  def to_s
    "Customer global"
  end

end


class Order

  class Customer
    def to_s
      "Customer within order"
    end
  end


  def initialize
    puts Customer.new
    puts ::Customer.new
  end


end

Order.new

will print out

Customer within order
Customer global
like image 116
Wolfgang Avatar answered Oct 23 '22 14:10

Wolfgang


When you do ::ModuleName::ClassName you're saying:

I want you to look for ::ModuleName::ClassName at the root namespace, ignoring if this code is found inside another module. So, it will always look for a class that's named as ::ModuleName::ClassName and nothing else

When you say it like this ModuleName::ClassName, you're saying:

I want you to look for ModuleName::ClassName but looking at the current scope first and then at the other scopes. So, if you have a module called MyModule and this my module references ModuleName::ClassName then first try to find MyModule::ModuleName::ClassName then try to resolve ::ModuleName::ClassName.

When I'm defining code like this I almost always use ::ModuleName::ClassName to avoid any naming conflicts.

like image 3
Maurício Linhares Avatar answered Oct 23 '22 13:10

Maurício Linhares