Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
npiv Avatar asked May 15 '11 21:05

npiv


People also ask

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

How do you reference a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Is it a Ruby module or class?

Ruby modules are a collection of methods, constants and classes. Unlike classes modules don't have instances; instead, you specify that you want to add the functionality of a particular module to that of a class.


2 Answers

::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.

like image 192
ctide Avatar answered Oct 25 '22 04:10

ctide


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).

like image 35
Julik Avatar answered Oct 25 '22 03:10

Julik