简体   繁体   中英

ruby ::Module or just Module

I'm slowly making my way through the rails source, to get a better grip on ruby and rails in general. In the following rails class test_case.rb

the line is

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

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

 class TestCase < Test::Unit::TestCase

It may seem trivial, but these things matter picking up a new language. The tests still run for ActiveSupport if I remove the leading :: so what does it do... :P

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

The latter case ( Test::Unit::TestCase ) doesn't ensure that Test is a toplevel module, it could be a class, for example. It means that most of the time, it'll work, but you could accidentally break it.

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 would error out since your Test constant available to the class you are creating has no Unit constant in it. If you address it by :: this is like the leading slash in a path.

There is also a special case for using these - you can be evaluating your code in something else than the default root namespace, and there you actually need the double colon to address classes like ::Object (usually to monkeypatch them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM