Ruby :: Module or just a module

I slowly make my way through the source of the rails to better capture the ruby ​​and the rails in general. In the following rails, the class test_case.rb

line

class TestCase < ::Test::Unit::TestCase 

and I was wondering if there is a difference with doing the following

  class TestCase < Test::Unit::TestCase 

It may seem trivial, but it all takes on a new language. Tests are still running for ActiveSupport if I remove the leading :: so that it does ...: P

+8
ruby ruby-on-rails
source share
2 answers

::Test ensures that you get a toplevel module named Test.

The latter case ( Test::Unit::TestCase ) does not guarantee that Test is a top-level module, it can be a class, for example. This means that most of the time it will work, but you can accidentally break it.

+8
source share

Imagine you have this code

 module UserTesting class Test # Details about a simple test end class TestCases < Test::Unit::TestCase end end # => NameError: uninitialized constant UserTesting::Test::Unit 

This will result in an error, since your test constant, available for the class you are creating, does not have a constant Unit in it. If you access it through :: it looks like a leading slash along the way.

There is also a special case for using them - you can evaluate your code in something other than the default root namespace, and you really need a double colon to refer to classes like :: Object (usually for their monkey) .

+5
source share

All Articles